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



我有一个HTML表,我正在尝试使用模糊搜索和部分匹配来过滤它。我试过很多JS库,但它们似乎并不能同时提供这两种过滤器选项。我试过FuzySort.js、FlexSearch.js和其他一些。有人知道有哪个图书馆能做到这一点吗?

基础:

  • MySQL存储数据
  • 前端显示表格
  • 管理员有一个独立的前端,可以将数据添加/删除/编辑到MySQL
  • JavaScript在前端过滤/排序/搜索表客户端

要求:

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

预期结果:如果。。。

  • 表行#1具有名称";名称1">
  • 表行#2具有名称";名称2">
  • 表行#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,这样它们就不是全局的。

最新更新