我有一个附加到两个不同搜索输入的函数。在我的for循环中,我循环遍历行,并根据使用的搜索输入过滤第一列或第三列。在循环中有两个if语句感觉不对,我该怎么重构呢?
// attach keyup event listener to input
document.getElementById("search-rule").addEventListener("keyup", searchVehicle);
document.getElementById("search-region").addEventListener("keyup", searchVehicle);
var ruleEl = document.getElementById("search-rule");
function searchVehicle(event) {
// convert input to uppercase
var filter = event.target.value.toUpperCase();
// select rows in tbody
var rows = document.querySelector("#myTable tbody").rows;
// loop through the rows
// if the input searches by rule, search the first column
// else search the 3rd column (region)
// if in input show the row, if not in input, hide row
for (var i = 0; i < rows.length; i++) {
if (event.target === ruleEl) {
var colRule = rows[i].cells[0].textContent.toUpperCase();
} else {
var colRule = rows[i].cells[2].textContent.toUpperCase();
}
if (colRule.indexOf(filter) > -1) {
rows[i].style.display = "";
} else {
rows[i].style.display = "none";
}
}
}
答案 0 :(得分:1)
您可以使用三元语句来设置显示属性:
rows[i].style.display = (colRule.indexOf(filter) > -1) ? "" : "none";
我还会在函数顶部声明colRule
var并仅将其分配给循环,而不是重新声明它。