我试图让我的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表格加载时是隐藏的,每次我搜索时它都会显示匹配的内容,但当我删除搜索框中的文本时,该表格不会恢复隐藏状态。相反,它会显示整个表。
发布于 2019-06-06 02:59:23
您将表设置为block,但从未将其设置回none。使用现有的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
发布于 2019-06-06 03:04:08
当未找到任何内容时,您忘记将表的显示样式设置为none:
table.style.display = "none";
以下是完整的工作代码:
var theButton = document.getElementById("b1");
theButton.onclick = myFunction1;
theButton = document.getElementById("b2");
theButton.onclick = myFunction2;
function myFunction1() {
myFunction ('something');
}
function myFunction2() {
myFunction ();
}
function myFunction (myInput) {
var table = document.getElementById("dvExcel");
var tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td ) {
if (myInput) {
table.style.display = "block";
tr[i].style.display = "";
} else {
table.style.display = "none";
tr[i].style.display = "none";
}
}
}
}
#dvExcel {
display: none;
}
<h3>
table show/hide test
</h3>
<table id="dvExcel"><tr><td>This is the table. It is visible now.</td></tr></table>
<button id="b1">
find something
</button>
<button id="b2">
don't find anything
</button>
https://stackoverflow.com/questions/56466397
复制相似问题