HTML和JS中的搜索栏

问题描述 投票:0回答:1

我创建了一个HTML表,其中包含有关一个国家的许多信息。现在,我希望用户能够在此表中搜索诸如“区域”之类的信息。

function selectRow() {
  var input, filter, table, trs, td;
  input = document.getElementById("search");
  filter = input.value.toUpperCase();
  table = document.getElementById("dataRows");
  trs = table.getElementsByTagName("tr");
  for (let index = 0; index < trs.length; index++) {
    td = trs[index].getElementsByTagName("td")[0];
    if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
      trs[index].display = "";
    } else {
      trs[index].display = "none";
    }
  }
}
<input type="text" id="search" onkeyup="selectRow()" placeholder="Search.." />

<table id="dataRows">
  <tr>
    <th>Attributes</th>
    <th>Value</th>
  </tr>
  <tr>
    <td>Name</td>
    <td>Australia</td>
  </tr>
  <tr>
    <td>Area</td>
    <td>7,741,220.00</td>
  </tr>
  <tr>
    <td>Population</td>
    <td>25,466,459</td>
  </tr>
</table>

但是当我尝试使用它时,出现错误:“未捕获的TypeError:无法读取未定义的属性'innerHTML'”我不知道为什么未定义td。

javascript html searchbar
1个回答
0
投票

<script>
function myFunction() {
  // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName('li');

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0];
    txtValue = a.textContent || a.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}
</script>

使用这样的代码来获得最佳结果,并且没有任何错误

© www.soinside.com 2019 - 2024. All rights reserved.