简体   繁体   English

如何使用JavaScript搜索HTML表格中的单元格?

[英]How to search cells in a HTML table using JavaScript?

I have the following table in this Fiddle . 我在小提琴中有下表。

As you can see, is a table with two columns each row and this table will be updated, in the future, with more two row columns. 如您所见,是一个每行两列的表,将来将更新此表,并增加两行。

My goal here is to use the search filter to show rows at the top of the table. 我的目标是使用搜索过滤器在表顶部显示行。 You can see this functionality in the Fiddle. 您可以在小提琴中看到此功能。 If you type: "Weekly" the rows Daily and Weekly will appear. 如果您输入:“每周”,则将出现“每日”和“每周”行。 But Daily first, not Weekly. 但是每天第一,而不是每周一次。

But what I want is everytime I find a cell with a certain word I want it to appear at the first cell of the table. 但是我想要的是每次我找到一个带有特定单词的单元格时都希望它出现在表格的第一个单元格中。 In this case if I search "Weekly" I want that in the first cell of the first row. 在这种情况下,如果我搜索“每周”,则希望在第一行的第一个单元格中进行搜索。

How can I do this with JavaScript? 如何使用JavaScript做到这一点? Here I'll let my Javascript code (In Fiddle's too): 在这里,我将使用我的Javascript代码(也在Fiddle中):

function search() {
  var input, checkfilter, filter, table, tr, td, i;
  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];
        td1 = tr[i].getElementsByTagName("td")[1];
    if (td || td1) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1 
          || td1.innerHTML.toUpperCase().indexOf(filter) > -1){
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

Thank you very much for your help. 非常感谢您的帮助。 I really appreciate the job is doing here in Stackoverflow. 我真的很感谢Stackoverflow在这里所做的工作。

I don't understand if you are asking a question or proposing a solution? 我不明白您是要提出问题还是提出解决方案?

getElementById('foobar') is a way to manipulate objects in the DOM. getElementById('foobar')是一种操作DOM中对象的方法。 For example here is something I use to quickly set up a PR template: 例如,以下是我用来快速设置PR模板的内容:

function () {
    var e = document.getElementById('pull_request_body');
    if (e) {
        e.value += 'Insert pull request template here';
    }
};

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

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