如何让JavaScript中动态生成的按钮click点击事件正常生效?
问题根因
- jQuery 直接使用
click()方法绑定事件时,只会对代码执行时刻已经存在于DOM树中的元素生效,你后续动态新增的表格行及内部的删除按钮是后续插入页面的,没有被绑定点击事件,所以点击无响应。 - 你给所有新增的行和删除按钮都设置了固定ID
tableRow、removeTableRow,HTML规范要求ID全局唯一,重复ID会导致元素选择逻辑异常,就算绑定成功也只能操作第一个匹配ID的元素。
修改步骤
- 将动态行和删除按钮的固定ID替换为类名,避免ID重复冲突
- 使用事件委托绑定删除事件,把事件绑定到页面初始就存在的父元素(这里用你的表格
#books-detail-table即可,性能最优),匹配指定类名的删除按钮触发逻辑 - 删除逻辑改为获取当前点击按钮所属的表格行,精准删除对应行,避免误删
修改后完整代码
<script> // 把固定ID替换为类名 let newRowContent = '<tr class="table-row">'; newRowContent += '<td>'; newRowContent += '<div class="form-group">'; newRowContent += '<select class="form-control" name="book">'; newRowContent += '@foreach( $books as $row )'; newRowContent += '<option value="{{ $row->id}}">{{ $row->title}}</option>'; newRowContent += '@endforeach'; newRowContent += '</select>'; newRowContent += '</div>'; newRowContent += '</td>'; newRowContent += '<td>'; newRowContent += '<div class="form-group">'; newRowContent += '<input type="number" class="form-control form-control-sm" placeholder="Qty">'; newRowContent += '</div>'; newRowContent += '</td>'; newRowContent += '<td>'; // 替换按钮ID为类名 newRowContent += '<button type="button" class="btn btn-sm btn-outline-danger remove-table-row">'; newRowContent += '<span data-feather="trash"></span>'; newRowContent += '</button>'; newRowContent += '</td>'; newRowContent += '</tr>'; $('#addTableRow').click(function() { $(newRowContent).appendTo($('#books-detail-table')); feather.replace(); }); // 改用事件委托绑定删除事件,绑到初始就存在的表格父元素上 $('#books-detail-table').on('click', '.remove-table-row', function() { // 找到当前按钮所属的整行删除 $(this).closest('.table-row').remove(); }) </script>
内容的提问来源于stack exchange,提问作者jhenryj09
相关产品推荐
相关产品推荐

