【问题标题】:searching text within Html table在 Html 表格中搜索文本
【发布时间】:2016-12-01 02:43:59
【问题描述】:

我只是在谷歌上搜索找到一个可以用来在 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”。

【问题讨论】:

  • 为什么不对其他单元格应用另一种 CSS 样式,例如不同的颜色?我认为用户可以看到其他值,但是搜索到的数据必须是有据可查的。
  • 这是个好主意,但我尝试创建一些隐藏/显示未突出显示的内容。

标签: javascript jquery html html-table


【解决方案1】:

这比你做的要简单得多。

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>

【讨论】:

    猜你喜欢
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多