本文介绍了使用jQuery删除动态生成的表行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的代码借助Jquery添加和删除表行 添加功能可以正常工作,但只有在删除第一行
the code below add and remove table row with the help of Jquery the add function works fine but the remove only work if I remove the first row
<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;
});
任何人都可以给我解释为什么我只能删除第一行吗?非常感谢
can anyone give me the explanation why I can only remove the first row ?thank so much
推荐答案
您需要使用事件委托,因为这些按钮在加载时不存在:
You need to use event delegation because those buttons don't exist on load:
http://jsfiddle.net/isherwood/Z7fG7/1/
$(document).on('click', 'button.removebutton', function () { // <-- changes
alert("aa");
$(this).closest('tr').remove();
return false;
});
这篇关于使用jQuery删除动态生成的表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!