【问题标题】:Search/ filter function javascript does not work搜索/过滤功能 javascript 不起作用
【发布时间】:2021-01-04 12:53:07
【问题描述】:

我想修改我在W3school上看到的代码,该代码是为了生成过滤/搜索功能。 原代码是

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

下面的代码旨在将输入与锚元素的 data-caption 属性进行比较,但它不起作用。谁能指出什么是错的?非常感谢!

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";
    }
  }
}

【问题讨论】:

  • Ahoj,虽然我认为我可以看到问题并帮助您解决问题,但这个问题对其他人没有太大帮助。我建议对您进行更多分析和更具体的问题,而不是“这块代码不起作用”。将其分解为多个步骤,对所涉及的变量进行一些调试打印输出,并尝试找出代码的哪一部分没有达到您的期望:) 您的橡皮鸭
  • 抱歉,我可能没有明确说明,实际上我知道我的代码有什么问题(getAttribute('data-caption')),但我不知道如何解决它。我理解您的意图不仅仅是给出答案,或者您能否给我一些解决方法的提示?
  • a 是什么?一个“a”元素。现在它是一个属性。橡皮鸭子想指出元素的行为不像属性,它们没有相同的属性。
  • 谢谢!你的提示确实有帮助!

标签: javascript html search filter


【解决方案1】:

尝试删除 .getAttribute('data-caption'),也许它会有所帮助,因为 W3Schools 不在他们的代码中使用它。

【讨论】:

  • 感谢您的回答,但我希望搜索功能将输入与锚元素的数据标题进行比较,这就是我添加 getAttribute 方法的原因。我可以知道为什么这样的添加会导致函数停止运行吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多