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

使用JS实现表格筛选并添加No Results Found无结果提示的问题

实现方案

核心逻辑如下:

  • 每次触发搜索前先移除之前插入的无结果提示行,避免重复生成
  • 完成原有筛选逻辑后,统计当前可见的表格行数量
  • 可见行数量为0时,插入包含No Results Found的提示行

修改后的完整代码:

//Function for searching products
$(document).ready(function(){
    $("#productInput").on("keyup", function() {
        let value = $(this).val().toLowerCase();
        // 先移除已有的无结果提示行,避免重复添加
        $("#productTable tr.no-result-row").remove();
        
        // 原有筛选逻辑,同时统计匹配成功的行
        let visibleRows = $("#productTable tr").filter(function() {
            let isMatch = $(this).text().toLowerCase().indexOf(value) > -1;
            $(this).toggle(isMatch);
            return isMatch;
        });

        // 匹配结果为0时插入提示行
        if(visibleRows.length === 0) {
            // 此处colspan的值需替换为你表格实际的列总数,保证提示行占满整行
            $("#productTable").append(`<tr class="no-result-row"><td colspan="3">No Results Found</td></tr>`);
        }
    });
});

适配带表头的表格

如果你的表格把表头放在<thead>标签内,仅需要筛选<tbody>中的内容,可以使用下方调整后的版本,避免表头被隐藏或计入统计:

$(document).ready(function(){
    $("#productInput").on("keyup", function() {
        let value = $(this).val().toLowerCase();
        $("#productTable tbody tr.no-result-row").remove();
        
        let visibleRows = $("#productTable tbody tr").filter(function() {
            let isMatch = $(this).text().toLowerCase().indexOf(value) > -1;
            $(this).toggle(isMatch);
            return isMatch;
        });

        if(visibleRows.length === 0) {
            $("#productTable tbody").append(`<tr class="no-result-row"><td colspan="3">No Results Found</td></tr>`);
        }
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:27:03