简体   繁体   English

使用for循环和多个if else语句重构函数

[英]Refactor function with for loop and multiple if else statements

I have a function that is attached to two different search inputs. 我有一个附加到两个不同搜索输入的函数。 In my for loop i loop through the rows and either filter the first or third column based on which search input was used. 在我的for循环中,我循环浏览各行,然后根据所使用的搜索输入过滤第一列或第三列。 Having two if statements in the loop doesn't feel right, how can i refactor this? 在循环中有两个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";
    }      
  }
}

You can use a ternary statement to set the display property: 您可以使用三元语句来设置显示属性:

rows[i].style.display = (colRule.indexOf(filter) > -1) ? "" : "none";

I would also declare the colRule var at the top of the function and only assign it in the loop, rather than redeclare it. 我还将在函数顶部声明colRule var,仅在循环中分配它,而不是重新声明它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM