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

如何修改代码实现通过类名查找表格列(替代文本匹配)

修改搜索逻辑:从匹配TD文本到匹配TD的Class属性

Alright, let's adjust your code to search by <td> class instead of text content. Here's how you can modify it step by step:

核心修改思路

Your original code calls a search() function that looks for text inside <td> elements. We need to rewrite that function to check if a <td> has the class matching your search input instead.

修改后的完整代码

$(".searchbox").on('keyup', function () {
    if ($(this).val() != '') {
        search(this);
    } else {
        $(".data").show();
        $.each($(".searchbox"), function () {
            if ($(this).val() != '') {
                $(this).keyup();
            }
        });
    }
});

// Updated search function to match TD class attributes
function search(input) {
    const searchValue = $(input).val().trim();
    
    // Hide all rows first
    $(".data").hide();
    
    // Find TDs with the matching class, then show their parent row
    $(".data td").filter(function() {
        // Use hasClass() for reliable check (works even if TD has multiple classes)
        return $(this).hasClass(searchValue);
        
        // Optional: If you need EXACT class match (no extra classes), use this instead:
        // return $(this).attr('class') === searchValue;
    }).closest(".data").show();
}

关键修改点解释

  1. filter()逻辑替换:

    • Instead of checking the text inside <td>, we now use hasClass(searchValue) to verify if the <td> contains the class you entered in the search box. This is the most reliable method because it accounts for elements with multiple classes (e.g., <td class="priority-high active">).
    • If you need an exact match (where the <td>'s class attribute is exactly equal to your search input, no extra classes), swap out hasClass() with $(this).attr('class') === searchValue.
  2. 忽略大小写(可选):
    If you want the search to be case-insensitive, adjust the filter logic like this:

    return $(this).attr('class')?.toLowerCase().includes(searchValue.toLowerCase());
    

    The ?. operator prevents errors if a <td> has no class attribute.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:54:11