【问题标题】:Altering w3 example table filter to search multiple columns更改 w3 示例表过滤器以搜索多个列
【发布时间】:2017-12-04 18:31:05
【问题描述】:

我在 PHP 中使用每行交替数量的列的大表工作。行和列是由一系列“foreach”循环从 MYSQL 数据库调用事物生成和填充的。

我对 PHP/HTML 和 MYSQL 非常满意。

我正在尝试使用 Javascript 为该表创建一些“快速过滤器”。

我从w3上的一个例子开始,如下

    <script> 
     function myFunction() {
 // Declare variables 
  var input, filter, table, tr, td, i;
 input = document.getElementById("myInput");
 filter = input.value.toUpperCase();
 table = document.getElementById("myTable");
 tr = table.getElementsByTagName("tr");

 // Loop through all table rows, and hide those who don't match the 
search query
 for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
  if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
    tr[i].style.display = "";
  } else {
    tr[i].style.display = "none";
  }
 } 
}
}
</script>

这与输入标签一起使用,您可以在其中使用用户输入文本进行搜索。我的示例不再像示例那样,但我真正的问题是

如何在所有列(实际上是表格的整个文本)中进行搜索,这部分代码控制搜索哪一列。

 td = tr[i].getElementsByTagName("td")[0];

末尾的 [0] 表示它仅搜索“第一”列。将 0 更改为另一个数字将更改为搜索整个表的相应列。

我觉得必须有一种简单的方法可以将其扩展到多个列。我对 JS 完全陌生,所以我真的在这里摸索。

我已经尝试了所有我能想到的基本方法,比如只更改以下内容的数字:

[0,1,2,3,4]// [0-4]// [0][1][2] 

这些简单的东西似乎都不是我想要的。它要么选择要搜索的列的最后列出的数字,要么完全破坏它!

【问题讨论】:

    标签: javascript php html filter html-table


    【解决方案1】:

    你必须嵌套循环! 我不得不使用一个额外的变量 occurrence 来检查是否出现在同一行的任何 td 中。 所以如果没有,可以隐藏该行!

      function myFunction() {
          // Declare variables 
          var input, filter, table, tr, td, i, occurrence;
    
          input = document.getElementById("myInput");
          filter = input.value.toUpperCase();
          table = document.getElementById("myTable");
          tr = table.getElementsByTagName("tr");
    
          // Loop through all table rows, and hide those who don't match the search query
         for (i = 0; i < tr.length; i++) {
             occurrence = false; // Only reset to false once per row.
             td = tr[i].getElementsByTagName("td");
             for(var j=0; j< td.length; j++){                
                 currentTd = td[j];
                 if (currentTd ) {
                     if (currentTd.innerHTML.toUpperCase().indexOf(filter) > -1) {
                         tr[i].style.display = "";
                         occurrence = true;
                     } 
                 }
             }
             if(!occurrence){
                 tr[i].style.display = "none";
             } 
         }
       }
    

    currentTd[j] 就是你要找的! 但是由于你可能不知道一行中有多少个 td,所以你必须使用 for 循环!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 2017-04-02
      相关资源
      最近更新 更多