我试图让我的 HTML 表格隐藏加载,它只显示与用户搜索相应匹配的“命中”,只要没有进行搜索,表格就会恢复隐藏状态。
<html>
<table id="dvExcel"></table>
</html>
<style>
#dvExcel{
display: none;
}
</style>
<script>
function myFunction() {
//this is the search function
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
and store
table = document.getElementById("dvExcel");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td ) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
table.style.display = "block";
tr[i].style.display = "";
}else {
tr[i].style.display = "none";
}
}
}
}
</script>
我的 HTML 表格加载是隐藏的,每次我搜索时它都会显示匹配项,但是当我删除搜索框中的文本时表格不会恢复隐藏状态。相反,它会显示整个表格。
最佳答案
您将表设置为阻塞但从未将其设置回无。使用现有的 for 循环,添加一个检查以查看是否找到任何命中。如果没有找到隐藏整个表,而不仅仅是行。
var foundHit = false; // Add this
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td ) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
table.style.display = "block";
tr[i].style.display = "";
foundHit = true; // Add this
}else {
tr[i].style.display = "none";
}
}
}
if (!foundHit) table.style.display = "none"; // Add this
关于javascript - 搜索完成后如何隐藏我的 HTML 表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56466397/