简体   繁体   English

搜索/过滤 function javascript 不起作用

[英]Search/ filter function javascript does not work

I would like to modify the code I saw on the W3school and the code is to generate a filter/ search function.我想修改我在 W3school 上看到的代码,代码是生成过滤器/搜索 function。 the original code is原始代码是

<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>

The code below is meant to compare the input with the data-caption attribute of the anchor element but it does not work.下面的代码旨在将输入与锚元素的 data-caption 属性进行比较,但它不起作用。 Can anyone kindly point out what is wrong?谁能指出什么是错的? Thanks so much!非常感谢!

function search() {   
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('search-input');
  filter = input.value.toUpperCase();
  ul = document.getElementById('search-opt');
  li = ul.getElementsByTagName('li');
  for (i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0].getAttribute('data-caption');
    txtValue = a.textContent || a.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

Try removing the .getAttribute('data-caption') , maybe it helps because W3Schools doesn't use it in their code.尝试删除.getAttribute('data-caption') ,也许它会有所帮助,因为 W3Schools 不在他们的代码中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM