我正在尝试动态添加和删除表中的某些行,并成功添加动态行。但我无法删除动态创建的行,其中可以使用jQuery删除由html创建的行。我听到附上我的代码
HTML:
<table id="customFields">
<tr>
<td><input type="text" name="chk_nom" id="chk_nom"></td>
<td><a class='rem' id="remScnt" href="javascript:void(0);">Remove</a></td>
</tr>
<tr>
<td> <a href="javascript:void(0);" class="addCF">Add</a></td>
</tr>
</table>
jQuery的:
$(document).ready(function(){
$('.rem').click(function() {
$(this).closest('tr').remove();
});
$('.addCF').click(function(){
$("#customFields").append('<tr><td><input type="text" name="chk_nom" id="chk_nom"></td><td><a class="rem" id="remScnt" href="javascript:void(0);">Remove</a></td></tr>');
});
});
提前致谢...
答案 0 :(得分:3)
更改
$('.rem').click(function() {
$(this).closest('tr').remove();
});
到
$('#customFields').on('click','.rem',function() {
$(this).closest('tr').remove();
});
这样事件处理程序也适用于在设置事件处理后添加到“#customFields”的元素。
答案 1 :(得分:1)
$(#customFields).on('click','.rem',function() {
$(this).closest('tr').remove();
});
基本上.click会在页面加载时添加处理程序。
因为您在页面加载后添加这些项目,所以javascript不知道它们在那里。
.on是一个“直播”活动,意味着它可以随时工作 - 即使是新添加的项目!