繁体   English   中英

搜索完成后,如何隐藏HTML表格?

[英]How can I hide my HTML table, when a search is finished?

我试图让我的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

当找不到任何内容时,您忘记将表的显示样式设置为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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM