使用jQuery删除动态生成的表行

时间:2014-04-23 15:38:11

标签: jquery html

下面的代码在Jquery的帮助下添加和删除表行  添加功能工作正常,但只有删除第一行

才能删除
<table>
    <tr>
    <td><button type="button"  class="removebutton" title="Remove this row">X</button>
</td> 
         <td><input type="text" id="txtTitle" name="txtTitle"></td> 
         <td><input type="text" id="txtLink" name="txtLink"></td> 
    </tr>
</table>
<button id ="addbutton">Add Row</button>

和脚本

 var i = 1;
$("#addbutton").click(function() {
  $("table tr:first").clone().find("input").each(function() {
    $(this).val('').attr({
      'id': function(_, id) {return id + i },
      'name': function(_, name) { return name + i },
      'value': ''               
    });
  }).end().appendTo("table");
  i++;
});

$('button.removebutton').on('click',function() {
    alert("aa");
  $(this).closest( 'tr').remove();
  return false;
});

任何人都可以解释为什么我只能删除第一行吗? 非常感谢

6 个答案:

答案 0 :(得分:38)

您需要使用事件委派,因为加载时不存在这些按钮:

http://jsfiddle.net/isherwood/Z7fG7/1/

 $(document).on('click', 'button.removebutton', function () { // <-- changes
     alert("aa");
     $(this).closest('tr').remove();
     return false;
 });

答案 1 :(得分:4)

使用事件委派,因为您正在创建动态行。

$(document).on('click','button.removebutton', function() {
    alert("aa");
  $(this).closest('tr').remove();
  return false;
});

Live Demo

答案 2 :(得分:3)

克隆时,默认情况下不会克隆事件。添加的行没有附加到它们的事件处理程序。如果你打电话给clone(true),那么它也应该处理它们。

http://api.jquery.com/clone/

答案 3 :(得分:1)

一个简单的解决方案是在函数中封装按钮事件的代码,并在添加TR时调用它:

 var i = 1;
$("#addbutton").click(function() {
  $("table tr:first").clone().find("input").each(function() {
    $(this).val('').attr({
      'id': function(_, id) {return id + i },
      'name': function(_, name) { return name + i },
      'value': ''               
    });
  }).end().appendTo("table");
  i++;

  applyRemoveEvent();  
});


function applyRemoveEvent(){
    $('button.removebutton').on('click',function() {
        alert("aa");
      $(this).closest( 'tr').remove();
      return false;
    });
};

applyRemoveEvent();

<强> http://jsfiddle.net/Z7fG7/2/

答案 4 :(得分:0)

我知道这很旧,但是我使用了与此类似的功能...

deleteRow: function (ctrl) {

    //remove the row from the table
    $(ctrl).closest('tr').remove();

}

...具有这样的标记...

<tr>
<td><span id="spDeleteRow" onclick="deleteRow(this)">X</td>
<td> blah blah </td>
</tr>

...效果很好

答案 5 :(得分:-1)

  $(document.body).on('click', 'buttontrash', function () { // <-- changes
    alert("aa");
   /$(this).closest('tr').remove();
    return false;
});

这非常有效,不需要document.body

相关问题