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

多表头表格JS过滤:仅显示匹配数据对应的thead

多表头表格过滤时仅显示匹配数据对应的表头

我有一个包含多个<thead>的大型表格,现有一段简单的JS函数用于过滤表格数据,但过滤时会显示所有表头部分。需要实现:过滤表格数据的同时,仅显示包含匹配<tr>元素的对应<thead>部分。

当前代码

JavaScript

$(document).ready(function() {
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tbody tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});

HTML

<div class="col-md d-inline">
  <input type="text" class="form-control" aria-label="Small" aria-describedby="inputGroup-sizing-sm" placeholder="搜索.." id="myInput">
</div>
<table id="myTable" class="table table-sm table-bordered table-hover">
  <thead class="bg-primary">
    <tr>
      <th colspan="3">部门信息</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>名称 - IT</td>
      <td>电话 - 1111111</td>
      <td>邮箱 - mail@mail.com</td>
    </tr>
  </tbody>
  <thead class="bg-primary">
    <tr>
      <th colspan="3">部门信息2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>名称 - 财务</td>
      <td>电话 - 1111112</td>
      <td>邮箱 - finance@mail.com</td>
    </tr>
    <tr>
      <td>名称 - 财务2</td>
      <td>电话 - 1111113</td>
      <td>邮箱 - finance2@mail.com</td>
    </tr>
  </tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

解决方案

核心思路是:先控制表格行的显示/隐藏,再根据每个<tbody>是否有可见行,来控制其对应的前一个<thead>的显示状态,同时处理输入为空时恢复全部显示的情况。

修改后的JavaScript代码:

$(document).ready(function() {
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    var $table = $("#myTable");
    
    // 先显示所有thead和tbody,避免残留隐藏状态
    $table.find('thead, tbody').show();
    
    if (value.trim() === '') {
      return; // 输入为空时直接返回,保持全部显示
    }
    
    // 遍历每个tbody,处理内部行的显示/隐藏
    $table.find('tbody').each(function() {
      var $tbody = $(this);
      var hasVisibleRow = false;
      
      // 处理当前tbody下的所有行
      $tbody.find('tr').each(function() {
        var $tr = $(this);
        var isMatch = $tr.text().toLowerCase().indexOf(value) > -1;
        $tr.toggle(isMatch);
        if (isMatch) hasVisibleRow = true;
      });
      
      // 如果当前tbody没有可见行,隐藏它和对应的前一个thead
      if (!hasVisibleRow) {
        $tbody.hide();
        $tbody.prev('thead').hide();
      }
    });
  });
});

代码说明

  • 每次输入时先重置所有<thead>和<tbody>为显示状态,避免之前的过滤残留影响
  • 输入为空时直接退出,确保所有内容都显示
  • 逐个处理每个<tbody>:
    • 检查当前<tbody>内是否有匹配的行,标记状态
    • 没有匹配行时,同时隐藏该<tbody>和它前面紧邻的<thead>
    • 有匹配行时,保持<thead>和<tbody>显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:05:38