i具有连接到两个不同搜索输入的函数。在我的循环中,我循环穿过行,并根据使用搜索输入的第一个或第三列过滤。如果循环中有两个语句感觉不正确,我该如何重构?
// 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";
}
}
}
您可以使用三元语句设置显示属性:
rows[i].style.display = (colRule.indexOf(filter) > -1) ? "" : "none";
我还会在功能顶部声明colRule
VAR,而不是在循环中分配,而不是重新列出。