使用javascript在多个表上创建过滤器/搜索功能

时间:2018-01-25 14:56:45

标签: javascript html input

我已经能够按照以下教程,允许我在1个表上创建一个过滤器。

https://www.w3schools.com/howto/howto_js_filter_table.asp https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table

我希望能够为同一输入过滤多个表。

所以:

  • 1输入表格
  • 多个定义
  • 所有表格上的相同过滤器
  • 如果匹配则显示/隐藏在所有表格上

这可能吗?

1 个答案:

答案 0 :(得分:2)

这可能会对你有所帮助。只需将属性data-table添加到所有表中即可。并迭代它们。



<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

.mytable {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ddd;
  font-size: 18px;
}

.mytable th, .mytable td {
  text-align: left;
  padding: 12px;
}

.mytable tr {
  border-bottom: 1px solid #ddd;
}

.mytable tr.header, .mytable tr:hover {
  background-color: #f1f1f1;
}
</style>
</head>
<body>

<h2>My Customers</h2>

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<table id="myTable" class="mytable" data-name="mytable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Canada</td>
  </tr>
</table>
    <br><br>
<table id="myTable2" class="mytable" data-name="mytable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>UK</td>
  </tr>
</table>

<script>
function myFunction() {
  var input, filter, table, tr, td, i,alltables;
    alltables = document.querySelectorAll("table[data-name=mytable]");
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  alltables.forEach(function(table){
      tr = table.getElementsByTagName("tr");
      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>

</body>
</html>
&#13;
&#13;
&#13;