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

如何使用jQuery删除表格中除选中行外的所有tbody行?

用jQuery删除表格中除选中行外的所有行

嘿,这个需求其实挺常见的,我来给你几个实用的jQuery解决方案,刚好匹配你的员工列表场景~

场景一:每行自带「Select」按钮

假设你的表格每行末尾都有一个Select按钮,点击后只保留当前行,删除<tbody>里其他所有行,代码可以这么写:

<!-- 示例表格结构 -->
<table>
  <thead>
    <tr><th>员工姓名</th><th>操作</th></tr>
  </thead>
  <tbody>
    <tr>
      <td>张三</td>
      <td><button class="select-btn">Select</button></td>
    </tr>
    <tr>
      <td>李四</td>
      <td><button class="select-btn">Select</button></td>
    </tr>
    <!-- 更多员工行 -->
  </tbody>
</table>
$('.select-btn').on('click', function() {
  // 找到当前点击按钮所在的行
  const selectedRow = $(this).closest('tr');
  // 定位到对应的tbody,获取所有行并排除选中行,最后删除
  selectedRow.closest('tbody').find('tr').not(selectedRow).remove();
});

场景二:全局「Select」按钮+复选框选中行

如果是先通过复选框选中某一行,再点击全局的Select按钮来保留选中行,代码可以调整为:

<!-- 示例表格结构 -->
<table>
  <thead>
    <tr><th>选择</th><th>员工姓名</th></tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="checkbox" class="row-checkbox"></td>
      <td>张三</td>
    </tr>
    <tr>
      <td><input type="checkbox" class="row-checkbox"></td>
      <td>李四</td>
    </tr>
    <!-- 更多员工行 -->
  </tbody>
</table>
<button class="global-select-btn">选中并保留该行</button>
$('.global-select-btn').on('click', function() {
  // 获取所有被选中复选框对应的行
  const selectedRows = $('.row-checkbox:checked').closest('tr');
  
  // 加个判断:如果没选中任何行,提示用户
  if (selectedRows.length === 0) {
    alert('请先选择一行哦~');
    return;
  }
  
  // 定位到tbody,删除除选中行外的所有行
  selectedRows.closest('tbody').find('tr').not(selectedRows).remove();
});

额外小提示

  • 一定要用closest('tbody')来定位范围,避免误删<thead>里的表头行
  • 如果担心误操作,可以加个判断:当<tbody>里只剩一行时,提示用户无需删除
  • 代码里的类名(比如select-btn)可以根据你实际的HTML结构调整,确保选择器准确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:41:33