我试图让我的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表加载为隐藏状态,每次搜索时都会显示匹配项,但是当我在搜索框中删除文本时,该表不会回到隐藏状态。而是显示整个表格。
答案 0 :(得分:0)
您将表设置为阻止,但不要将其重新设置为无。使用现有的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
答案 1 :(得分:0)
找不到任何内容时,您忘记将表的显示样式设置为无:
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>