首页 > 其他分享 >html页面实现搜索关键字展示

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

时间:2022-10-16 18:46:34浏览次数:59  
标签:www 遍历 tr 关键字 html td com 页面

直接上代码

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/

标签:www,遍历,tr,关键字,html,td,com,页面
From: https://www.cnblogs.com/chaishengblog/p/16796735.html