克隆按钮不适用于单击功能

猛禽

在下面的代码片段中,我有一个输入和一个删除按钮。它们可以被克隆,每个删除按钮都有一个功能,告诉我哪个输入正试图被删除。

奇怪的是,当我运行代码片段时,它运行良好。

在我的浏览器中,克隆的按钮不会调用该函数,只有原始按钮会调用。此外,标题“删除”仅出现在第一个按钮上,即使我将鼠标悬停在任何其他按钮上也是如此。

什么可能导致这个问题?

我正在使用代码段中所有内容的相同版本。

$("#clone").click(function() {
  var currentCount = $("#tablePhones tbody tr").length;
  var newCount = currentCount + 1;

  $('#tablePhones tbody>tr:last').clone(true).insertAfter('#tablePhones tbody>tr:last');
  $('#tablePhones tbody>tr:last').find("input, a").each(function() {
    var newId = $(this).attr("id").replace("_" + currentCount, "_" + newCount);
    var newName = $(this).attr("name").replace("_" + currentCount, "_" + newCount);
    $(this).attr("id", newId).attr("name", newName);
    if ($(this).is("input")) {
      $(this).val("");
    }
  });
});

$(".btn.remove").click(function() {
  name = $(this).attr("name");
  console.log(name);
});
td .btn.aligned {
  position: absolute;
  margin-top: 7px;
  float: right;
  margin-left: 5px;
}

td input {
  float: left;
  margin-bottom: 10px;
}
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://use.fontawesome.com/a06b1c7829.js"></script>

<a id="clone" class="btn btn-primary">
  <i class="fa "></i> Clone
</a>

<table id="tablePhones" class="table table-hover">
  <thead class="thead-inverse">
    <th>Phone numbers</th>
  </thead>
  <tbody>
    <tr>
      <td>
        <div class="row col-xs-3">
          <input type="text" name="phone_1" id="telefono1_1" class="form-control" />
          <a title="Remove" name="removephone_1" id="removephone_1" class="btn btn-danger btn-xs aligned remove"><span class="fa fa-times">
          </span>
          </a>
        </div>
      </td>
    </tr>
  </tbody>
</table>

维杰

必须是与新创建/插入的 DOM 元素的事件侦听器附件相关的问题。尝试使用事件委托技术如下:

$(document).on("click", ".btn.remove" ,function() {
  name = $(this).attr("name");
  console.log(name);
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章