【问题标题】:Search through multiple columns of a table搜索表格的多个列
【发布时间】:2018-07-12 03:26:40
【问题描述】:

我目前有一个表格,它通过每个表格的一列进行过滤和搜索,但是我不确定如何编辑我的函数以便将搜索应用于表格的所有列。 这是我的功能,也是我的一张桌子:

  function myFunction(){
  var td, i;
  var input = document.getElementById("myInput");
  var filter = input.value.toUpperCase();
  var table = document.getElementById("myTable");
  var 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";
      }
    }
  }
}

<table className="table table-bordered" id="table2a">
          <tbody>
          <tr><th> Consumer System: </th>
          <td>System1 </td>
          <td>System2 </td>
          </tr>

          <tr>
          <th>Consumer Dev App Name: </th>
          <td> To be on-boarded </td>
          <td> To be on-boarded </td>
          </tr>

          <tr>
          <th> Contact Email Distribution </th>
          <td>TBD </td>
          <td> TBD </td>
          </tr>
          </tbody>
          </table>

【问题讨论】:

  • 在你的外部 for 循环中,你需要用一个内部循环替换这一行 td = tr[i].getElementsByTagName("td")[0]; 以遍历 &lt;tr&gt; 中的所有 &lt;td&gt; 元素
  • for(j = 0; j &lt; td.length; j++) 是这样的你在说什么? @mjw

标签: javascript css html-table


【解决方案1】:

对于表中的每一行,您将需要一个内部循环来遍历当前 tr 中的每个 td

function myFunction(){
  var td, i, tdArr, j;
  var input = document.getElementById("myInput");
  var filter = input.value.toUpperCase();
  var table = document.getElementById("myTable");
  var tr = table.getElementsByTagName("tr");

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

【讨论】:

  • 非常感谢!正是我想要做的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多