首页 > 解决方案 > 调整表过滤器 Javascript

问题描述

我正在尝试调整一些当前允许用户在输入中输入文本的 javascript,然后它将隐藏所有不包含该文本的行。现在它只检查第一列,但我希望它检查第 1 列和第 2 列:

HTML:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:20%;">Country</th>
    <th style="width:20%;">Size</th>
  </tr>
  <tr>
    <td>Joe Smith</td>
    <td>Canada</td>
    <td>Medium</td>
  </tr>
    <tr>
    <td>Jane Doe</td>
    <td>Germany</td>
    <td>Small</td>
  </tr>
</table>

So in the simple example below, you could type either Jane or Germany to have that row show filter.

JAVASCRIPT:

<script>
function myFunction() {
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }       
  }

}
</script>

标签: javascripthtml-table

解决方案


尝试这个:

for (i = 0; i < tr.length; i++) {
   var found = false;
   for (j = 0; j < 3; j++){
      td = tr[i].getElementsByTagName("td")[j];
      if (td) {
          txtValue = td.textContent || td.innerText;
          if (txtValue.toUpperCase().indexOf(filter) > -1) {
              found = true;
              break;
          }
       }
    }
    if (found) {
        tr[i].style.display = "";
    } else {
        tr[i].style.display = "none";
    }
  }

在列上创建一个内部循环,检查每一列。找到文本后,中断循环。循环后,检查找到的属性,设置路由显示。


推荐阅读