如何修改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
相关产品推荐
相关产品推荐

