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

JavaScript HTML表格搜索:清空搜索框后移除行样式类的方法

解决表格搜索后清空输入框时移除匹配样式类的问题

嘿,这个问题我之前也碰到过!其实解决起来很简单,核心思路就是在每次执行搜索逻辑前,先统一移除所有行的样式类,然后再根据当前搜索内容去匹配添加。这样不管搜索框是空还是有内容,都能保证样式是干净的状态。

原生JavaScript实现示例

假设你的搜索输入框ID是searchInput,表格行在<tbody>下,要添加的样式类是highlight,可以这么写:

const searchInput = document.getElementById('searchInput');
// 提前缓存表格行节点,避免重复查询DOM
const tableRows = document.querySelectorAll('tbody tr');

searchInput.addEventListener('input', function() {
  const searchTerm = this.value.trim().toLowerCase();
  
  // 第一步:统一移除所有行的高亮样式类
  tableRows.forEach(row => {
    row.classList.remove('highlight');
  });
  
  // 如果搜索框为空,直接结束逻辑
  if (!searchTerm) return;
  
  // 第二步:筛选匹配的行并添加样式类
  tableRows.forEach(row => {
    const rowText = row.textContent.toLowerCase();
    if (rowText.includes(searchTerm)) {
      row.classList.add('highlight');
    }
  });
});

jQuery实现示例

如果项目里用了jQuery,代码会更简洁:

// 缓存表格行节点
const $tableRows = $('tbody tr');

$('#searchInput').on('input', function() {
  const searchTerm = $(this).val().trim().toLowerCase();
  
  // 先清空所有高亮类
  $tableRows.removeClass('highlight');
  
  if (!searchTerm) return;
  
  // 匹配内容并添加样式
  $tableRows.filter(function() {
    return $(this).text().toLowerCase().includes(searchTerm);
  }).addClass('highlight');
});

关键逻辑说明

这个方案的核心是先清除再添加:

  • 每次输入框内容变化时,第一步就把所有行的目标样式类移除,确保初始状态是干净的
  • 如果搜索框为空,直接终止后续逻辑,避免不必要的DOM操作
  • 只有当搜索框有内容时,才去筛选匹配的行并添加样式类

如果你的表格数据量特别大,还可以考虑给匹配逻辑加个防抖(比如延迟300ms再执行搜索),减少DOM操作的频率,提升性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 06:59:08