簡體   English   中英

使用for循環和多個if else語句重構函數

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

我有一個附加到兩個不同搜索輸入的函數。 在我的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";
    }      
  }
}

您可以使用三元語句來設置顯示屬性:

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

我還將在函數頂部聲明colRule var,僅在循環中分配它,而不是重新聲明它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM