2017-03-24 89 views
0

使用W3C網站中的表格過濾器,您如何修改搜索td = tr[i].getElementsByTagName("td")[0];,以查看不僅僅是其當前構建的第一列[0]使用JavaScript表格過濾器過濾多個列

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


    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"; 
     } 
    } 
    } 
} 
+0

TD = T R [i]於.getElementsByTagName( 「TD」)[0]; - 將此變量替換爲0 – dev8080

回答

0

已經有一個循環遍歷行(trs)。所以我剛剛添加了一個循環來遍歷列(tds)。

第二個for循環遍歷全部每行中的列。它可以進行修改以適應OP的要求。

嘗試此(對於所有列):

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


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

     tds = tr[i].getElementsByTagName("td"); 
     var found = false;  //----------used to see if any col returns a positiv match 
     //---second loop that goes over all tds in a tr ---can be modified as required to go over only certain tds 
     for (j = 0; j < tds.length; j++){ 
      td = tds[j]; 
      if (td) { 
        if (td.innerHTML.toUpperCase().indexOf(filter) > -1) { 
        found = true; 
        break; 
       } 
      } 
     } 

    if(found) 
     tr[i].style.display = ""; 
    else 
     tr[i].style.display = "none"; 

    } 
    } 
+0

請更詳細地解釋您爲解決問題所做的工作。 –