如何实现jQuery表格搜索无匹配结果时显示‘No results found’?
表格过滤无匹配结果时显示提示文本
实现方案
- 提前在页面中添加一个默认隐藏的提示元素,用于展示无匹配信息
- 在过滤逻辑中统计匹配成功的表格行数量
- 根据匹配行数动态控制提示元素的显示/隐藏
完整代码示例
HTML结构(需新增提示元素)
<!-- 搜索输入框 --> <input type="text" id="searchBar" placeholder="搜索表格内容..."> <!-- 目标表格 --> <table> <thead> <tr> <th>列名1</th> <th>列名2</th> </tr> </thead> <tbody id="tableData"> <tr> <td>测试数据1</td> <td>详情内容1</td> </tr> <tr> <td>测试数据2</td> <td>详情内容2</td> </tr> </tbody> </table> <!-- 无匹配提示(默认隐藏) --> <div id="noResults" style="display:none; color: #666; margin-top: 12px;">No results found</div>
修改后的jQuery代码
$(document).ready(function() { $('#searchBar').on('keyup', function() { var value = $(this).val().toLowerCase(); // 过滤数据行并收集匹配项 var matchedRows = $('#tableData tr').filter(function() { var isMatch = $(this).text().toLowerCase().indexOf(value) > -1; $(this).toggle(isMatch); return isMatch; }); // 根据匹配行数切换提示显示状态 $('#noResults').toggle(matchedRows.length === 0); }); });
关键细节说明
matchedRows会存储所有匹配成功的表格行,通过filter方法的返回值收集- 使用
toggle(matchedRows.length === 0)实现提示元素的智能显示:匹配数为0时展示提示,否则隐藏 - 如果你的表头行也在
<tbody>中,需要调整过滤范围为数据行(比如$('#tableData tr:gt(0)')),避免表头被过滤影响统计结果
内容的提问来源于stack exchange,提问作者SINEAD AJAX
相关产品推荐
相关产品推荐

