简体   繁体   English

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

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

I can't figure out the following;我无法弄清楚以下内容; I have a simple JS script that filters/hides rows of the table based on a search value.我有一个简单的 JS 脚本,可以根据搜索值过滤/隐藏表格的行。 How can I search two columns td0 and td1 at the same time?如何同时搜索两列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";
              }
            } 
      }
    }

I'm sure that this is not the right approach though.我确信这不是正确的方法。 I am trying to search both td0 and td1 at the same time.我正在尝试同时搜索td0td1 Any help would be greatly appreciate it!任何帮助将不胜感激!

Javascript can only run single thread. Javascript 只能运行单线程。 If you really want to run these two codes together at the same time, you need to use Web Workers to use threading, but I think this will be overkill for this task.如果你真的想同时运行这两个代码,你需要使用Web Workers来使用线程,但我认为这对于这个任务来说有点过头了。

You can somehow run it together by using setTimeout , but in reality this will not run in parallel because it is single threaded.您可以通过使用setTimeout以某种方式一起运行它,但实际上这不会并行运行,因为它是单线程的。 Note: this is a hacky way of doing this.注意:这是一种 hacky 方式。

Example:例子:

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

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

I suggest you use $.Deferred , much better.我建议你使用$.Deferred ,更好。

Web workers: link Deferred: link Web 工人: 链接延迟: 链接

I just figure it out.我只是想通了。 A super simple JQuery:一个超级简单的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)
    });
  });
});

I don't even know how I missed this.我什至不知道我是怎么错过的。 Thanks for help anyways!无论如何感谢您的帮助!

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

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