簡體   English   中英

如何創建過濾器搜索以從表的兩列中搜索數據?

[英]How to create a filter search to search data from two columns in a table?

現在,搜索僅從第一列開始。 我已經從w3schools獲取了代碼,這是代碼:

function myFunction() {
// Declare variables
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

嘗試這個

myFunction() {
  // Declare variables 
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    //Column 1
    td_1 = tr[i].getElementsByTagName("td")[0];
    //Column 2
    td_2 = tr[i].getElementsByTagName("td")[1];
    if (td_1 || td_2) {
      if (td_1.innerHTML.toUpperCase().indexOf(filter) > -1 || td_2.innerHTML.toUpperCase().indexOf(filter)> -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    } 
  }
}

工作提琴

您將需要擴展循環以包括多個列:

//Get the column count
var columnCount = table.getElementsByTagName("tr")[0].childNodes.length;

for (i = 0; i < tr.length; i++) {

    for (j = 0; j < columnCount; j++) {

        td = tr[i].getElementsByTagName("td")[j];

        if (td) {

                var tempText;

                if(td.childNodes[1].getAttribute('id')){

                    tempText = td.childNodes[1].getAttribute('id');

                }                   
                else {

                    tempText = td.innerHTML.toUpperCase();

                }

                try {
                    if (tempText.indexOf(filter) > -1) {
                        tr[i].style.display = "";
                    } else {
                        tr[i].style.display = "none";
                    }
                }
                catch(err) {}

        }

    }

}

暫無
暫無

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

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