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

表格多列输入框筛选功能失效,请求技术排查修复

表格列单独搜索功能修复

我有一个用于编辑人员信息的带输入框的表格,想要实现每列单独搜索,仅显示包含搜索内容的行,但该功能无法正常工作。

原代码存在以下问题:

  • 两个搜索函数重名myfunction,后定义的函数会覆盖前一个,导致只有第二个搜索框能触发逻辑
  • 第一个函数中,getElementsByClassName("myTable")返回的是元素集合,不能直接调用getElementsByTagName,需指定集合中的第一个表格
  • 搜索目标错误:要匹配的是td内输入框的内容,原代码中第一个函数取的是td的文本内容,第二个函数错误获取了索引为2的input,且判断匹配的条件indexOf(filter) > 1有误(应判断是否存在,即> -1)
  • 获取输入框内容应使用value属性,而非textContent/innerText,因为input的内容存储在value中

修复后的完整代码:

HTML部分

<table id="someTable" class="myTable">
    <!-- 表头行 -->
    <tr>
        <td>父亲姓名</td>
        <td>证件编号</td>
        <td><input autocomplete="off" onkeyup="searchColumn(0)" id="myInput" placeholder="جستجو ..." /></td>
        <td><input autocomplete="off" onkeyup="searchColumn(1)" id="myInput2" placeholder="جستجو ..." /></td>
    </tr>
    <!-- 数据行(实际由后端渲染) -->
    @for (int i = 0; i < Model.Count; i++)
    {
        <tr>
            <td><input autocomplete="off" type="text" style="width: 110px" name="[@i].FatherName" value="@Model[i].FatherName" /></td>
            <td><input autocomplete="off" type="text" style="width: 110px" name="[@i].PersonSryalPoshtCartMlie" value="@Model[i].PersonSryalPoshtCartMlie" /></td>
            <td></td>
            <td></td>
        </tr>
    }
</table>

JavaScript部分

function searchColumn(columnIndex) {
    // 根据列索引获取对应的搜索框
    const inputId = columnIndex === 0 ? "myInput" : "myInput2";
    const input = document.getElementById(inputId);
    const filter = input.value.toUpperCase();
    const table = document.getElementById("someTable");
    const trList = table.getElementsByTagName("tr");

    // 遍历所有数据行(跳过表头行,从索引1开始)
    for (let i = 1; i < trList.length; i++) {
        const tr = trList[i];
        // 获取当前行对应列的td,再取里面的input元素
        const td = tr.getElementsByTagName("td")[columnIndex];
        if (td) {
            const inputElement = td.getElementsByTagName("input")[0];
            if (inputElement) {
                const txtValue = inputElement.value.toUpperCase();
                // 判断是否包含搜索关键词
                tr.style.display = txtValue.indexOf(filter) > -1 ? "" : "none";
            }
        }
    }
}

代码说明

  • 统一使用一个searchColumn函数,通过传入列索引区分不同的搜索列
  • 明确指定要搜索的列索引,避免错误的元素定位
  • 遍历数据行时跳过表头(从索引1开始),防止表头被隐藏
  • 使用input.value获取输入框的实际内容,确保搜索匹配正确
  • 修复了表格元素的获取方式,避免集合操作错误

表格搜索界面

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 21:44:55