2016-11-29 96 views
0

我只是用googling找到一個腳本,我可以用它在HTML表格中查找文本。在Html表格中搜索文本

就像我創建了一個有很多列和行的學生名稱表。我有一個好劇本太那個什麼顯示我嘗試搜索,但它顯示全行...

function searchSname() { 
 
    var input, filter, found, table, tr, td, i, j; 
 
    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"); 
 
     for (j = 0; j < td.length; j++) { 
 
      if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) { 
 
       found = true; 
 
      } 
 
     } 
 
     if (found) { 
 
      tr[i].style.display = ""; 
 
      found = false; 
 
     } else { 
 
      tr[i].style.display = "none"; 
 
     } 
 
    } 
 
}
<input id='myInput' onkeyup='searchSname()' type='text'> 
 

 
<table id='myTable'> 
 
    <tr> 
 
     <td>AB</td> 
 
     <td>BC</td> 
 
    </tr> 
 
    <tr> 
 
     <td>CD</td> 
 
     <td>DE</td> 
 
    </tr> 
 
    <tr> 
 
     <td>EF</td> 
 
     <td>GH</td> 
 
    </tr> 
 
</table>

但是知道我在找做一些改變,以顯示一切我搜索確切文本而不是全行像它會顯示文本,我鍵入搜索和隱藏其他無與倫比的全部....

請讓我知道是否有可能顯示文本只有我鍵入搜索表內?就像我試圖找到學生姓名「AB」那麼它應該只顯示AB而不是「AB BC」。

+0

你爲什麼不是其他的CSS樣式應用到其他細胞像diferent顏色?我認爲用戶可以看到其他值,但搜索到的數據必須有證據。 – regisls

+0

多數民衆贊成在一個不錯的主意,但我嘗試創建一些隱藏/顯示不突出顯示。 –

回答

0

這比你做的要簡單得多。

var cells = document.querySelectorAll("#myTable td"); 
 
var search = document.getElementById("myInput"); 
 

 
search.addEventListener("keyup", function(){ 
 

 
    for(var i = 0; i < cells.length; ++i){ 
 
    // This line checks for an exact match in a cell against what the 
 
    // user entered in the search box 
 
    //if(cells[i].textContent.toLowerCase() === search.value.toLowerCase()){ 
 
    
 
    // This checks for cells that start with what the user has entered 
 
    if(cells[i].textContent.toLowerCase().indexOf(search.value.toLowerCase()) === 0){  
 
     cells.forEach(function(element){ 
 
      element.style.display = "none"; 
 
     }); 
 
     cells[i].style.background = "yellow"; 
 
     cells[i].style.display = "table-cell"; 
 
     break; 
 
    } else { 
 
     cells[i].style.background = "white"; 
 
     cells.forEach(function(element){ 
 
      if(cells[i] !== element){ 
 
      element.style.display = "table-cell"; 
 
      } 
 
     }); 
 
    }  
 
    } 
 

 
});
table, td { border:1px solid black; border-collapse: collapse;}
<input id='myInput'> 
 

 
<table id='myTable'> 
 
    <tr> 
 
     <td>AB</td> 
 
     <td>BC</td> 
 
    </tr> 
 
    <tr> 
 
     <td>CD</td> 
 
     <td>DE</td> 
 
    </tr> 
 
    <tr> 
 
     <td>EF</td> 
 
     <td>GH</td> 
 
    </tr> 
 
</table>