下面的代码在Jquery的帮助下添加和删除表行,add函数工作正常,但删除只有在我删除第一行时才能工作
<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>
Run Code Online (Sandbox Code Playgroud)
和脚本
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;
});
Run Code Online (Sandbox Code Playgroud)
任何人都可以给我解释为什么我只能删除第一行?非常感谢
ish*_*ood 38
您需要使用事件委派,因为加载时不存在这些按钮:
http://jsfiddle.net/isherwood/Z7fG7/1/
$(document).on('click', 'button.removebutton', function () { // <-- changes
alert("aa");
$(this).closest('tr').remove();
return false;
});
Run Code Online (Sandbox Code Playgroud)
您应该使用事件委托,因为您正在创建动态行。
$(document).on('click','button.removebutton', function() {
alert("aa");
$(this).closest('tr').remove();
return false;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
99830 次 |
| 最近记录: |