【问题标题】:Javascript search and filter tableJavascript 搜索和过滤表
【发布时间】:2021-03-09 09:51:07
【问题描述】:

我想编写一个 js 函数,让我可以在表格中进行搜索。 我只想显示那些包含任何

中的搜索文本的行

虽然我能够使其仅适用于特定列,但我没有成功适用于整行。所以我猜它在内部 for 循环中的某个地方。知道我哪里做错了吗?

感谢您的支持! 这是我的代码:

function myFunction() {
var input, filter, table, tr, td, i, txtValue, allText, j;
input = document.getElementById("ipt-Search"); //my input text field where I enter the search term
filter = input.value.toUpperCase();
table = document.getElementById("tbl-RS"); // the table I want to search and filter
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
    allText = "";
    for (j = 0; j < tr.cells.length; j++) {
        td = tr[i].getElementsByTagName("td")[j];
        if (td) {
            allTest = all Test + " " + td.textContent || td.innerText;
        }
    }
    if (allText.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
    } else {
        tr[i].style.display = "none";
    }
}

}

【问题讨论】:

    标签: javascript filter html-table


    【解决方案1】:

    我看到你找到了答案。我可以添加一个更新的解决方案吗?此解决方案使用 ES6。很高兴关注javascript的进步。

    const myFunction = () => {
      let txtValue, filter;
      const input = document.getElementById("myInput");
      const table = document.getElementById("myTable");
      filter = input.value.toUpperCase();
      for (tr of table.getElementsByTagName("tr")) 
        for(td of tr.getElementsByTagName("td"))
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1){
                    tr.style.display = "";
                    break;
                }
                else 
                    tr.style.display = "none"; 
            }   
        }
    

    【讨论】:

      【解决方案2】:

      找到答案:

      <script>
      function myFunction() {
          var input, filter, table, tr, td, i, txtValue;
          input = document.getElementById("ipt-Search");
          filter = input.value.toUpperCase();
          table = document.getElementById("tbl-RS");
          tr = table.getElementsByTagName("tr");
      
          for (i = 1; i < tr.length; i++) {
          // Hide the row initially.
          tr[i].style.display = "none";
      
          td = tr[i].getElementsByTagName("td");
          for (var j = 0; j < td.length; j++) {
            cell = tr[i].getElementsByTagName("td")[j];
            if (cell) {
              if (cell.innerHTML.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
                break;
              }
            }
          }
      }
      }
      </script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-25
        • 2010-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-15
        • 1970-01-01
        • 2020-05-30
        相关资源
        最近更新 更多