我正在尝试创建一个switch语句来过滤表中过滤器的所有可能选项,但是当我在搜索栏中键入任何内容时,它无法识别情况。我不能对过滤器使用if ... else语句,因为我需要过滤器一起运行而不是一个运行。我尝试过更改变量的名称,以使其更清楚地表明我为每列指定一个var,但没有这种运气。任何见识将不胜感激!
var Caps = event.target.value.toUpperCase();
var Hyphen = event.target.value.replace(/[-]/g, "");
var rows = document.querySelector("#Catalogue").rows;
var firstCol = rows[i].cells[0].textContent.replace(/[-]/g, '');
var thirdCol = rows[i].cells[2].textContent.replace(/[-]/g, '');
var ColOne = rows[i].cells[0].textContent.toUpperCase();
var ColThree = rows[i].cells[2].textContent.toUpperCase();
function filterTable(event) {
for (var i = 1; i < rows.length; i++)
{if
(switch(true){
case (ColThree.indexOf(Caps) > -1 || thirdCol.indexOf(Hyphen) > -1):
rows[i].style.display = ""
break;
case (ColOne.indexOf(Caps) > -1 || firstCol.indexOf(Hyphen) > -1):
rows[i].style.display = "";
break;
case (ColOne.indexOf(Caps) > -1 && firstCol.indexOf(Hyphen) > -1):
rows[i].style.display = "";
break;
case (ColThree.indexOf(Caps) > -1 && thirdCol.indexOf(Hyphen) > -1):
rows[i].style.display = "";
})
else{
rows[i].style.display = "none"
}
}
}
document.querySelector('#myInput').addEventListener('keyup', filterTable,
false);
答案 0 :(得分:0)
这里有很多错误:
一种方法可能是:
// Edit : rows query can be done only once to save time
let rows = document.querySelectorAll('tr.items'); // or much precise query if needed
function check(event) {
let caps = event.target.value.toUpperCase();
let hyphen = caps.replace(/[-]/g, ""); // Edit : caps + hyphen will work
// Browse all rows to check if input matching and hide/show
// Fortunately row.textContent yields all texts values :)
for(let i = 0; i < rows.length; i++) {
let row = rows[i];
// test caps length to allow revert to all hidden when no text to match
if(caps.length && (row.textContent.indexOf(caps) >= 0 || row.textContent.indexOf(hyphen) >= 0)) {
row.style.display = null;
break; // process next row
}
row.style.display = 'none'; // Hide row (avoid an else)
}
}
document.getElementById('my-input').addEventListener('keyup', check, true);
table {
width:100%;
border-collapse: collapse
}
th, td {
border: 1px solid #000;
}
<p>Type here : <input type="text" id="my-input"></p>
<table>
<tr><th>Id</th><th>Row1</th><th>Row2</th></tr>
<tr class="items" style="display:none"><td>001</td><td>FOO</td><td>BAR</td></tr>
<tr class="items" style="display:none"><td>002</td><td>GOO</td><td>CAR</td></tr>
</table>
默认情况下,行是隐藏的,就像我假设的脚本中一样。项目值是001、002,FOO,BAR,GOO,CAR。随便玩吧。
好消息是您可以访问整个行的textContent,而无需查看单个tds,从而节省了很多时间。