html页面实现搜索关键字展示

直接上代码

html代码

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="搜索..">
 
<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Url</th>
  </tr>
  <tr>
    <td>Google</td>
    <td>www.google.com</td>
  </tr>
  <tr>
    <td>Runoob</td>
    <td>www.runoob.com</td>
  </tr>
  <tr>
    <td>Taobao</td>
    <td>www.taobao.com</td>
  </tr>
  <tr>
    <td>Baidu</td>
    <td>www.baidu.com</td>
  </tr>
</table>

js代码(可加script嵌入html)

function myFunction() {
  // 声明变量
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable"); //要找的所有元素的共同父结点
  tr = table.getElementsByTagName("tr"); //所有元素的共同父结点下的每一个元素的同类父结点
 
  // 循环遍历所有列表项,并隐藏那些与搜索查询不匹配的项
  for (i = 0; i < tr.length; i++) { //遍历每一个元素的同类父节点(如果不想遍历最后一个的话,可以选择tr.length-1不遍历最后一个。)
    td = tr[i].getElementsByTagName("td")[0]; //同类父节点下的要找的元素的具体位置
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none"; //不是的话就隐藏
      }
    }
  }
}

注意:选择的父节点要对,位置要对,甚至script的位置也要对。

这个菜鸟工具还是不错的 https://c.runoob.com/examples/

posted @   高柴小生  阅读(970)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示