You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery动态生成表格行删除功能失效问题解决指导求助

问题解决方法

删除功能失效有两个核心原因:

  1. HTML中id属性全局唯一,仅初始行的删除单元格设置了id="deleteRow",后续动态生成的行的删除单元格没有对应id,无法被选择器匹配。
  2. 直接使用$(选择器).click()的绑定方式仅对页面首次加载时已存在的DOM元素生效,后续动态插入的元素不会自动绑定该事件。

修改步骤

1. 替换id为可复用的class

把初始表格行中的删除单元格从id="deleteRow"改为class="deleteRow",同时给动态新增的行的删除单元格也加上相同的class。

2. 使用事件委托绑定删除事件

将删除事件绑定到页面初始就存在的表格父元素上,通过事件冒泡机制实现对所有新增行的事件监听。


修改后完整代码

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<table id="shipmentConsignment" class="table table-condensed table-striped table-bordered">
  <thead>
    <th class="text-center" scope="col" width="20%">Serial</th>
    <th class="text-center" scope="col" width="15%">ID</th>
    <th class="text-center" scope="col" width="15%">Code</th>
    <th class="text-center" scope="col" width="45%">Description</th>
    <th class="text-center" scope="col" width="5%"></th>
  </thead>
  <tbody>
    <tr>
      <td><input type="text" class="form-control" autocomplete="off" placeholder="Serial" name="serial"></td>
      <td></td>
      <td></td>
      <td></td>
      <!-- 这里把id替换为class -->
      <td class="deleteRow"><span class="glyphicon glyphicon-trash"></span></td>
    </tr>
  </tbody>
</table>
<button type="button" name="addRow" value="addRow" id="addRow" class="btn btn-primary">Add Item</button>

<script>
$(document).ready(function() {
  $("#addRow").click(function() {
    // 新增行的删除单元格也添加deleteRow类
    var markup = "<tr><td><input type=\"text\" class=\"form-control\" autocomplete=\"off\" placeholder=\"Serial\" name=\"serial\"></td><td></td><td></td><td></td><td class=\"deleteRow\"><span class=\"glyphicon glyphicon-trash\"></span></td></tr>";
    $("#shipmentConsignment").append(markup);
  });
  // 改用事件委托方式绑定删除事件
  $("#shipmentConsignment").on("click", ".deleteRow", function() {
    $(this).closest('tr').remove();
  });
});
</script>

内容的提问来源于stack exchange,提问作者user982124

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 19:24:04