简体   繁体   English

表格行中断按钮的jQuery克隆

[英]jQuery cloning of table row breaks button

I have a html table (Bootstrap 3) which has a button in its last td of each row. 我有一个html表(引导程序3),该表的每行最后一个td中都有一个按钮。 This button has a class btn-add-row . 此按钮具有btn-add-row In my Javascript I use (from this question): 在我的Javascript中,我使用(来自这个问题):

$('.btn-add-row').click(function() {
    var $tr = $(this).closest('tr');
    var $clone = $tr.clone();
    $clone.find('input').val('');
    $tr.after($clone);
});

Now, the row which is cloned also contains that specific button. 现在,克隆的行还包含该特定按钮。 It copies the button without issue, but when you click the button in the row which was added, the javascript is not executed. 它复制按钮没有问题,但是当您单击添加的行中的按钮时,不会执行javascript。 The copied button does have the class btn-add-row , and clicking buttons which were originally already on the page still work. 复制的按钮确实具有btn-add-row ,并且单击原来在页面上的按钮仍然可以使用。

How can I fix this issue? 如何解决此问题?

You have to options here. 您必须在这里选择。 First to add click handler for cloned row 首先为克隆行添加点击处理程序

function clickHandler() {
  var $tr = $(this).closest('tr');
  var $clone = $tr.clone();
  $clone.find('.btn-add-row').click(clickHandler);
  $clone.find('input').val('');
  $tr.after($clone);
}
$('.btn-add-row').click(clickHandler);

And the other to use event delegation 和另一个使用事件委托

$( "table" ).on( "click", ".btn-add-row", clickHandler);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM