如何实现表格在内容筛选完成前保持隐藏状态?
实现表格搜索前隐藏、搜索后显示的方案
要让表格在未进行搜索时保持隐藏,仅在用户通过搜索栏筛选后显示,你只需做两处关键修改:
1. 设置表格初始隐藏状态
直接在表格标签中添加style="display: none;",让页面加载时表格默认不显示:
<table border="1" cellpadding="0" id="studtable" style="display: none;">
2. 修改搜索函数逻辑
更新StudentSearch函数,增加表格显示/隐藏的判断逻辑:
- 搜索框为空时,隐藏表格
- 搜索框有内容时,先显示表格再执行筛选
- 可选:筛选无匹配结果时,再次隐藏表格(根据需求调整)
修改后的完整函数代码:
function StudentSearch() { var input, filter, table, tr, td, i, txtValue, foundHit = false; input = document.getElementById("studsearch"); filter = input.value.toUpperCase(); table = document.getElementById("studtable"); tr = table.getElementsByTagName("tr"); // 控制表格显示/隐藏 if (filter === "") { table.style.display = "none"; return; } else { table.style.display = ""; } // 执行行筛选逻辑 for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; foundHit = true; } else { tr[i].style.display = "none"; } } } // 可选:无匹配结果时隐藏表格,取消下面注释即可启用 // if (!foundHit) { // table.style.display = "none"; // } }
完整修改后的代码
整合所有修改后的完整代码如下:
<html> <head> </head> <div class="students"> Students <input type="text" id="studsearch" onkeyup="StudentSearch()" placeholder="Search Student Number"> <body> <table border="1" cellpadding="0" id="studtable" style="display: none;"> <tr> <th>Student No.</th> <th>Full Name</th> </tr> <tr id="stud1"> <td>1</td> <td>John</td> </tr> <tr id="stud2"> <td>2</td> <td>Mike</td> </tr> </table> </body> </div> <script> function StudentSearch() { var input, filter, table, tr, td, i, txtValue, foundHit = false; input = document.getElementById("studsearch"); filter = input.value.toUpperCase(); table = document.getElementById("studtable"); tr = table.getElementsByTagName("tr"); if (filter === "") { table.style.display = "none"; return; } else { table.style.display = ""; } for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; foundHit = true; } else { tr[i].style.display = "none"; } } } // 若需要无匹配时隐藏表格,取消下面注释 // if (!foundHit) { // table.style.display = "none"; // } } </script> </html>
逻辑说明
- 页面加载时,表格因
display: none默认隐藏 - 用户输入搜索内容时,表格自动显示并执行筛选
- 清空搜索框时,表格会再次隐藏
- 启用可选逻辑后,搜索无匹配结果时表格也会隐藏
内容的提问来源于stack exchange,提问作者Choi
相关产品推荐
相关产品推荐

