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

如何为表格中不符合输入值的行配置hidden类?

表格过滤器只作用于第一行的解决办法

我制作了一个表格过滤器,通过给不包含输入框值的行添加hidden类来实现筛选,但发现只有第一行被添加了该类,其他符合条件的行完全不受影响。如何让所有不符合输入值的行都添加hidden类?

原代码

HTML

<div class="container">
  <hr>
  <form class="form-search">
    <input class="form-control" id="form-control" type="text" name="fitrar" placeholder="Buscar Registros"
      autocomplete="off" autofocus />
    <a href="{% url 'registros' %}" id="id_btnlimpar" class="btn btn-light">Limpar</a>
  </form>
  </hr>
  <table class="table table-dark">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">CNPJ</th>
        <th scope="col">CPF</th>
        <th scope="col">Nome</th>
      </tr>
    </thead>
    <tbody>
      {% for registro in registros %}
      <tr>
        <td scope="row">{{ registro.id }}</td>
        <td scope="row"><a href="#modal{{registro.id}}" data-toggle="modal">{{ registro.cnpj }}</a></td>
        <td scope="row">{{ registro.cpf }}</td>
        <td scope="row">{{ registro.nome }}</td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>

JavaScript

const inputSearchRegistros = document.querySelector('.form-search input')
const tableRegistros = document.querySelector('.table tbody tr')

inputSearchRegistros.addEventListener('input', event => {
    const inputValue = event.target.value.trim()
    Array.from(tableRegistros.children)
        .filter(regs => !regs.textContent.includes(inputValue))
        .forEach(regs => {
            regs.classList.add('hidden')
        })
})

问题分析

  1. 元素获取错误:document.querySelector('.table tbody tr')只会返回匹配选择器的第一个元素,所以你只处理了第一行的子元素,完全没接触到其他行。
  2. 筛选逻辑错误:你给单元格添加hidden类,而不是给整行添加,这会导致行结构被破坏,正确的做法应该隐藏整个行。

修正后的代码

const inputSearchRegistros = document.querySelector('.form-search input')
// 获取所有表格行
const tableRows = document.querySelectorAll('.table tbody tr')

inputSearchRegistros.addEventListener('input', event => {
    const inputValue = event.target.value.trim().toLowerCase()
    
    // 遍历所有行
    tableRows.forEach(row => {
        // 获取整行的文本内容,转小写实现不区分大小写搜索
        const rowText = row.textContent.toLowerCase()
        // 判断是否包含输入值,不包含则添加hidden类,否则移除
        if (!rowText.includes(inputValue)) {
            row.classList.add('hidden')
        } else {
            row.classList.remove('hidden')
        }
    })
})

关键优化点

  • 使用document.querySelectorAll()获取所有元素,确保能遍历处理每一行。
  • 每次输入时根据条件动态添加/移除hidden类,避免之前的筛选结果残留。
  • 把文本转成小写,实现不区分大小写的搜索,提升用户体验。
  • 直接操作元素隐藏整行,而不是单个单元格,保证表格结构正常。

内容的提问来源于stack exchange,提问作者João Marcos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:15:40