使用JavaScript筛选/搜索表
首先,我不是JavaScript方面的专家,所以答案可能很简单,但目前我使用这个()教程来筛选一个表,但您只能在1列中搜索,所以在本例中只搜索名称或国家,但我希望同时在这两列中搜索 我需要在代码中更改什么使用JavaScript筛选/搜索表,javascript,search,filter,Javascript,Search,Filter,首先,我不是JavaScript方面的专家,所以答案可能很简单,但目前我使用这个()教程来筛选一个表,但您只能在1列中搜索,所以在本例中只搜索名称或国家,但我希望同时在这两列中搜索 我需要在代码中更改什么 function myFunction() { // Declare variables var input, filter, table, tr, td, i; input = document.getElementById("myInput"); filter = inp
function myFunction() {
// Declare variables
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
函数myFunction(){
//声明变量
var输入、过滤器、表格、tr、td、i;
输入=document.getElementById(“myInput”);
filter=input.value.toUpperCase();
table=document.getElementById(“myTable”);
tr=table.getElementsByTagName(“tr”);
//循环遍历所有表行,并隐藏与搜索查询不匹配的行
对于(i=0;i-1){
tr[i].style.display=“”;
}否则{
tr[i].style.display=“无”;
}
}
}
}
函数myFunction(){
//声明变量
var输入、过滤器、表格、tr、td、i;
输入=document.getElementById(“myInput”);
filter=input.value.toUpperCase();
table=document.getElementById(“myTable”);
tr=table.getElementsByTagName(“tr”);
//循环遍历所有表行,并隐藏与搜索查询不匹配的行
对于(i=0;i-1){
tr[i].style.display=“”;
}否则{
tr[i].style.display=“无”;
}
}
}
}
}
}您可以将返回的转换为数组(),然后使用该方法检查td
值中的“部分”值是否与您的过滤器匹配。如果存在匹配项,则显示它们。否则就把它们藏起来。代码如下:
function myFunction() {
const input = document.getElementById('myInput')
const filter = input.value.toLowerCase()
const table = document.getElementById('myTable')
const tr = [...table.getElementsByTagName('tr')]
tr.forEach((t) => {
const foundMatch = [...t.getElementsByTagName('td')].some((td) => {
return td.innerHTML.toLowerCase().indexOf(filter) > -1
})
if (foundMatch) {
t.style.display = ''
} else {
t.style.display = 'none'
}
})
}
在JSFIDLE上检查它的操作:
function myFunction() {
const input = document.getElementById('myInput')
const filter = input.value.toLowerCase()
const table = document.getElementById('myTable')
const tr = [...table.getElementsByTagName('tr')]
tr.forEach((t) => {
const foundMatch = [...t.getElementsByTagName('td')].some((td) => {
return td.innerHTML.toLowerCase().indexOf(filter) > -1
})
if (foundMatch) {
t.style.display = ''
} else {
t.style.display = 'none'
}
})
}