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

使用jQuery删除动态生成的表行,jquery,html,Jquery,Html,下面的代码在Jquery的帮助下添加和删除表行 “添加”功能可以正常工作,但只有在删除第一行时,“删除”才起作用 <table> <tr> <td><button type="button" class="removebutton" title="Remove this row">X</button> </td> <td><input type="text" id="t

下面的代码在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>
谁能给我解释一下为什么我只能删除第一行?
非常感谢

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


$(document).在('click','button.removebutton',function(){/上克隆时,默认情况下它不会克隆事件。添加的行没有附加事件处理程序。如果调用
clone(true)
,则它也应该处理这些事件


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

 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();

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

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

$(document.body)。在('click','buttontrash',function(){/上,我知道这是一个很旧的函数,但我使用了一个类似于此的函数

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>

X
废话

…而且效果很好

@isherwood-直到最近我才发现你的事件委派风格。我总是在创建对象后立即附加事件。我喜欢你的方式,因为我可以有一段代码,将我所有的事件处理都提前分组。这是个人喜好的问题,还是一种更有效的方式标准而非其他?我认为这取决于具体情况。对于下一个在代码中跌跌撞撞的开发人员来说,什么更清楚?很公平。我只是不想在跌跌撞撞之前设置它。:)对不起,这是Wilfredo的直接副本,但也不起作用。你有一半的意见。
  $(document.body).on('click', 'buttontrash', function () { // <-- changes
    alert("aa");
   /$(this).closest('tr').remove();
    return false;
});
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>