【问题标题】:Trying to use an array of indexes for a custom live search via js尝试通过 js 使用索引数组进行自定义实时搜索
【发布时间】:2022-01-25 03:11:19
【问题描述】:

这是我的代码...我基本上想制作这一行 (td = tr[i].querySelectorAll(".table-data")[0];) 我想要这部分...[0]变成这样 [0,5]

This is a sample code

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

【问题讨论】:

  • 不,不幸的是,这不是我想要做的。所以让我这样解释......我有一个使用 div 创建的表。虽然结构与传统桌子相同。我假设有 10 列。现在我想通过名称索引 0 和电话号码索引 5 来索引 AKA 搜索。如果我使用上面的代码执行 0 或 5,它工作正常。但我想索引两个不同的索引。根据输入。

标签: javascript arrays search


【解决方案1】:

您还需要遍历每一列并检查是否找到该值。

function myFunction() {
  var input, filter, table, tr, td, i, txtValue;
  input = document.querySelector("#myInput");
  filter = input.value.toUpperCase();
  table = document.querySelector("#myTable");
  tr = table.querySelectorAll(".row");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].querySelectorAll(".table-data");
    if (td) {
      let valid = false;
      for (t = 0; t < td.length; t++) {
        txtValue = td[t].textContent || td[t].innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
          valid = true;
        }
      }
      
      if (valid) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }       
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-02
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    相关资源
    最近更新 更多