繁体   English   中英

在两列上过滤/搜索表并隐藏行

[英]Filter/Search Table on Two Columns and Hide Rows

我无法弄清楚以下内容; 我有一个简单的 JS 脚本,可以根据搜索值过滤/隐藏表格的行。 如何同时搜索两列td0td1

function myFunction() {
      // Declare variables 
      var input, filter, table, tr, td0,td1, 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++) {
        td0 = tr[i].getElementsByTagName("td")[0];
        td1 = tr[i].getElementsByTagName("td")[1];

       // search first column
        if (td0) {
          txtValue = td0.textContent || td0.innerText;
          if (txtValue.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
          } else {
            tr[i].style.display = "none";
          }
        } 
       
       // search second column
       if (td1) {
              txtValue = td1.textContent || td1.innerText;
              if (txtValue.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
              } else {
                tr[i].style.display = "none";
              }
            } 
      }
    }

我确信这不是正确的方法。 我正在尝试同时搜索td0td1 任何帮助将不胜感激!

Javascript 只能运行单线程。 如果你真的想同时运行这两个代码,你需要使用Web Workers来使用线程,但我认为这对于这个任务来说有点过头了。

您可以通过使用setTimeout以某种方式一起运行它,但实际上这不会并行运行,因为它是单线程的。 注意:这是一种 hacky 方式。

例子:

setTimeout(function() {
    //search td1
},0);

setTimeout(function() {
    //search td2
},0);

我建议你使用$.Deferred ,更好。

Web 工人: 链接延迟: 链接

我只是想通了。 一个超级简单的JQuery:

$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});

我什至不知道我是怎么错过的。 无论如何感谢您的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM