首页 > 解决方案 > 可搜索的下拉菜单

问题描述

我在下拉列表中有一个项目列表,可以使用下拉列表中的搜索进行过滤。

<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Please select</button>
    <div id="myDropdown" class="dropdown-content">
    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
      <a href="#">Abyssinian</a>
      <a href="#">American Bobtail</a>
      <a href="#">Amercian Curl</a>
    </div>
</div>

而js...

function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

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

https://codepen.io/RSA_James/pen/LYZqYym

如果用户开始搜索某些内容并且没有匹配项,我所追求的是一种显示消息的方式。

任何帮助表示赞赏!谢谢

标签: javascripthtmljquery

解决方案


ES6 稍微缩小了代码:

function filterFunction(sText) {
  [...document.querySelectorAll('#myDropdown a')].forEach(elA => elA.classList.toggle('hide', !new RegExp(sText, 'gi').test(elA.textContent)));
  document.querySelector('#myDropdown span.err').classList.toggle('hide', document.querySelectorAll('#myDropdown a:not(.hide)').length);
}
.hide { display: none; } .err { color: red; }
<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Please select</button>
  <div id="myDropdown" class="dropdown-content">
    <input type="text" placeholder="Search.." id="myInput" oninput="filterFunction(this.value)">
    <a href="#">Abyssinian</a>
    <a href="#">American Bobtail</a>
    <a href="#">Amercian Curl</a>
    <span class="err hide">Nothing found</span>
  </div>
</div>


推荐阅读