javascript - 搜索完成后如何隐藏我的 HTML 表格?

标签 javascript html css

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

相关文章:

html - Textarea 元素未扩展其宽度的 100%

html - CSS:在绝对列表中每个 li 元素 +x 像素

javascript - 如何创建弹出式登录/注册?

javascript - Jquery选择器>无法选择自动对焦属性

javascript - <按钮类型 ="submit"> 在 IE 和 chrome 中的行为不同 : Why?

html - 为什么 flex 元素不缩小过去的内容大小?

html - 你能漂浮在跨度的右边吗?

css - Material ui 选项卡容器的动态高度

javascript - 如何将 VUE JS 项目迁移到 TypeScript

javascript - 使用哪个钩子(Hook)从节点数据插入 JavaScript 变量