要初始隐藏表格,只有在有搜索结果时才显示,可以给表格元素添加CSS样式,将其初始显示设置为“无”。然后,修改您的 JavaScript 代码以仅在至少有一个搜索结果时显示表格。
你可以试试这个:
<html>
<head>
<style>
#studtable {
display: none;
}
</style>
</head>
<body>
<div class="students">
Students
<input type="text" id="studsearch" onkeyup="StudentSearch()" placeholder="Search Student Number">
</div>
<table border="1" cellpadding="0" id="studtable">
<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>
<script>
function StudentSearch() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("studsearch");
filter = input.value.toUpperCase();
table = document.getElementById("studtable");
tr = table.getElementsByTagName("tr");
var foundHit = false;
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 = "";
} else {
table.style.display = "none";
}
}
</script>
</body>
</html>
使用此代码,表格将在页面首次加载时隐藏。只有至少有一个搜索结果时,才会显示表格。