使用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
相关产品推荐
相关产品推荐

