使用JavaScript来过滤/搜索表格 [英] Using JavaScript to filter/search table
问题描述
这个代码中需要改变什么?
function myFunction(){
//声明变量
var input,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];
if(td){
if(td.innerHTML.toUpperCase()。indexOf(filter)> -1){
tr [i] .style.display =;
} else {
tr [i] .style.display =none;
$ b $ / code $ / pre
解决方案您可以将 HTMLCollection
getElementsByTagName
到数组(检查这个答案的方法),然后使用 some
方法来检查 td
值与您的过滤器
匹配。如果有匹配,则显示它们。其他人隐藏他们。以下是代码:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $函数myFunction(){
常量输入= document.getElementById('myInput')
const filter = input.value.toLowerCase()
const table = document.getElementById('myTable')
const tr = [... table.getElementsByTagName('tr')] $ b $ (t)=> {
<返回td.innerHTML.toLowerCase()。indexOf(filter)> -1
})
if(foundMatch){
t.style.display =''
} else {
t.style.display ='none'
}
})
}
检查它在jsfiddle上的行动: https:// jsfiddle .net / marcusmonteiro / hsdyajbn / 2 / show /
First of all, I'm not an expert in JavaScript, so the answer will probably be simple, but currently I'm using this (https://www.w3schools.com/howto/howto_js_filter_table.asp) tutorial to filter through a table, but you can only search in 1 column, so in this example only for Name or Country, but I want to search in both columns at the same time.
What do I need to change in this code?
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";
}
}
}
}
You can convert the HTMLCollection
returned by getElementsByTagName
to an Array (check this answer for ways to do it) and then use the some
method to check if 'some' of the td
values match your filter
. If there is a match, display them. Else hide them. Here's the code:
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'
}
})
}
Check it in action on jsfiddle: https://jsfiddle.net/marcusmonteiro/hsdyajbn/2/show/
这篇关于使用JavaScript来过滤/搜索表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!