javascript - 可搜索的下拉菜单
问题描述
我在下拉列表中有一个项目列表,可以使用下拉列表中的搜索进行过滤。
<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
如果用户开始搜索某些内容并且没有匹配项,我所追求的是一种显示消息的方式。
任何帮助表示赞赏!谢谢
解决方案
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>
推荐阅读
- python-3.x - 我应该在哪里放置一个在 Django 中填充我的数据库的 Python 脚本?
- javascript - 如何开始创建 Web 服务?webix+js+revel
- python - 如何在不使用 discord.py 中的列表的情况下永久存储用户数据?
- excel - 选择列并应用格式
- python - python中getch的箭头键
- aws-sam - 适用于 VS Code SAM 本地代码的 AWS 工具包无法正常工作
- javascript - Vue路由器:注册完成后重定向到主页
- java - JDK 13 中的 xsl 版本 2.0?
- pandas - Pandas 运行时错误 /anaconda3/lib/python3.8/site-packages/pandas/__init__.py”,第 13 行 missing_dependencies
- node.js - 如何通过 JSON 数据创建新记录