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

如何修改jQuery代码实现仅搜索表格首列过滤行

问题:jQuery搜索仅匹配表格首列而非整行

我有一段基于jQuery的搜索代码,原本是根据搜索词过滤表格行,但现在会搜索整行所有列。我需要修改成仅搜索首列(col1),当首列不含搜索词时隐藏整行。目前输入“leather”时,会因为某行第5列有“leatherworker”而错误显示本该隐藏的行。

现有代码如下:

$(document).ready(function(){
        $('.search').on('keyup',function(){
            var searchTerm = $(this).val().toLowerCase();
            $('#craftTbl div.contentrow').each(function(){
                var lineStr = $(this).text().toLowerCase();
                if(lineStr.indexOf(searchTerm) === -1){
                    $(this).hide();
                    $(".descexpand").hide();
                    $(".rowCat").hide();
                    $(".rowSec").hide();
                }else{
                    $(this).show();
                }
            });
        });
    });

注:.rowCat、.rowSec、.descexpand类的行无需参与搜索,这部分功能目前正常。


修改后的代码

$(document).ready(function(){
    $('.search').on('keyup',function(){
        var searchTerm = $(this).val().toLowerCase();
        $('#craftTbl div.contentrow').each(function(){
            // 仅获取首列的文本内容进行匹配
            var firstColText = $(this).children().first().text().toLowerCase();
            if(firstColText.indexOf(searchTerm) === -1){
                $(this).hide();
                $(".descexpand").hide();
                $(".rowCat").hide();
                $(".rowSec").hide();
            }else{
                $(this).show();
            }
        });
    });
});

关键修改说明

  • 把原本获取整行文本的$(this).text()替换为$(this).children().first().text(),只提取当前行首列的内容
  • 仅对首列文本进行搜索匹配,避免其他列的内容干扰过滤结果
  • 原有隐藏非目标行的逻辑保持不变,无需调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:01:13