使用部分匹配过滤/搜索表格 - HTML 和 Javascript

詹姆斯·里德68

我有一个 HTML 表,我正在尝试使用模糊搜索和部分匹配对其进行过滤。我尝试过很多 JS 库,但它们似乎没有同时提供这两个过滤器选项。我尝试过 FuzySort.js、FlexSearch.js 等。有谁知道可以做到这一点的图书馆?

基础:

  • MySQL 存储数据。
  • 前端显示表格。
  • 管理员有一个单独的前端,允许他们向 MySQL 添加/删除/编辑数据。
  • 用于过滤/排序/搜索前端表客户端的 JavaScript。

要求:

  • 全文检索
  • 模糊搜索
  • 部分匹配。

预期结果:如果...

  • 表行 #1 的名称为“Name1”
  • 表第 2 行的名称为“Name2”
  • 表第 3 行的名称为“Name3”
  • 在搜索栏中,输入“Name1 Name3”它应该显示第 1 行和第 3 行

当前结果:

  • 在搜索栏中,当您键入“Name1 Name3”时,它不会显示任何结果。

当前代码

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

这是我的 JSFiddle: https ://jsfiddle.net/h7p8bzs0/

非常感谢任何帮助或指导。有没有人对什么库可以实现这些结果有任何建议,或者我如何调整上面的 JS 代码来做到这一点?

Ps:抱歉,我是新手,对使用 JSON、Node.JS、实际数据库等的选项感到不知所措。

本尼迪克特·伯姆

您可能想尝试以下 Javascript:

function myFunction() {
  const input = document.getElementById("myInput");
  const filters = input.value.toUpperCase().split(' '); // create several filters separated by space
  const table = document.getElementById("myTable");
  const tr = table.getElementsByTagName("tr");

  for (let i = 0; i < tr.length; i++) {
    const td = tr[i].getElementsByTagName("td")[1];

    if (td) {
      const txtValue = td.textContent || td.innerText;
        tr[i].style.display = "none"; // hide each row
        
      for (filter of filters) { // add the rows matching a filter
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
          tr[i].style.display = "";        
        }
      }       
    }
  }
}

这里发生的事情是我们创建了多个过滤器字符串来匹配,用空格分隔。一旦我们有至少一个过滤器,我们就会隐藏每一行,如果它匹配至少一个过滤器,我们会再次添加它。

哦,我对您的变量进行了一些重构:我们不需要事先声明符,我们希望将它们作为 let 或 const 使用,这样它们就不是全局的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章