通过jQuery动态添加的remove ID点击事件无法生效问题求助
解决动态添加表格后无法移除的问题
嘿,我一眼就看出你卡在哪了——动态新增的表格对应的移除按钮点了没反应对吧?这其实是jQuery里两个非常常见的小坑,我帮你把问题捋清楚,再给你修复好的代码:
问题根源
- 动态元素的事件绑定逻辑错误:你直接给
#remove绑定点击事件时,页面上只有初始加载的DOM元素,后来动态生成的#remove根本没被绑定到这个事件上——因为绑定操作只在页面加载完成时执行了一次,新元素是后来才出现的。 - 违反HTML唯一ID规则:你每次新增的移除按钮都用了
id="remove",但HTML里ID必须是全局唯一的,重复ID不仅会让选择器混乱,还可能引发其他莫名其妙的问题。
修复后的完整代码
jQuery 部分
$(document).ready(function(){ $('#AddMoreId').on('click', function(){ // 把重复的id="remove"改成class="remove",避免ID冲突 $('article:last').after('<article class="col100 left bggreen"><table><tr><th>ID</th><td><input type="number" id="id"></td></tr><tr><th>Menu in NPL</th><td><input type="text" id="menunep"></input></td></tr><tr><th>Menu in ENG</th><td><input type="text" id="menueng"></input></td></tr></table><section class="col100 left cursorpointer remove">Remove</section></article><br/>'); }); // 使用事件委托,绑定到已存在的document上,监听动态生成的.remove元素 $(document).on('click', '.remove', function(){ $(this).parents('article').remove(); }); });
HTML 部分(初始结构无需改动,仅需保证结构合法)
<article class="col100 left bggreen"> <table> <tr> <th> ID </th> <td> <input type="number" id="id"> </td> </tr> <tr> <th> Menu in NPL </th> <td> <input type="text" id="menunep"></input> </td> </tr> <tr> <th> Menu in ENG </th> <td> <input type="text" id="menueng"></input> </td> </tr> <tr> <td class="cursorpointer" colspan="2" id="AddMoreId">Add field </td> </tr> </table> </article>
关键修改说明
- 事件委托机制:用
$(document).on('click', '.remove', function(){...})代替直接绑定,这样不管是现在还是未来生成的.remove元素,点击事件都会生效——因为事件是绑定在已经存在的document上,通过事件冒泡触发目标元素的处理逻辑。 - 替换ID为Class:把移除按钮的
id="remove"改成class="remove",既保证了页面元素ID的唯一性,也适配了事件委托的选择器要求。
额外提个小细节:你原来用$('article:last').append(...)会把新的article嵌套到最后一个article内部,我改成了after()让新article放在最后一个article的外面,结构更合理;如果你确实需要嵌套结构,改回append也不影响移除功能。
内容的提问来源于stack exchange,提问作者Dipak
相关产品推荐
相关产品推荐

