javascript - 如何制作一个搜索列表,其中仅在用户搜索其确切值时才显示该元素
问题描述
所以,我有这个 html 代码来显示一个数字列表:
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="search">
<ul id="myUL">
<li><a href="#">006372145</a></li>
<li><a href="#">00021030</a></li>
<li><a href="#">9123981283</a></li>
<li><a href="#">190238120983</a></li>
<li><a href="#">128378</a></li>
<li><a href="#">1298488</a></li>
<li><a href="#">12983498</a></li>
</ul>
还有一个搜索栏,用户可以在其中输入文本。这是JS代码:
function myFunction() {
// Declare variables
var input, filter, ul, li, a, i;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName('li');
if(input.value.length == 0){
ul.style.display = "none";
return;
}else{
ul.style.display = "block";
}
// 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];
if (a.innerHTML.toUpperCase().indexOf(filter) == 0) {
li[i].style.display = "block";
}
else {
li[i].style.display = "none";
}
}
}
它过滤搜索输入以最终匹配一个数字,但我试图让它只显示完全相同的数字而不过滤其余数字以查看是否有任何匹配。
例如,我输入“00”并且没有数字显示,因为它不在列表中。但是,如果我输入了与列表中显示的数字完全匹配的数字。
解决方案
function applyFilter(userInput){
/*
Use css to set the display to none first
*/
var options = document.querySelectorAll("#myUL > a");
for(var i = 0; i < options.length; i++){
if(options[i].textContent.trim() == userInput.trim()){
// You can also convert to lowercase for more accurate result
options[i].style.display = "inline";
}
}
}
推荐阅读
- c++ - 返回类中的结构指针
- python - 如何创建具有 3 个不同 y 轴的 Seaborn 线图?
- neo4j - 我们可以匹配密码中的子图吗?
- javascript - 更改从锚选项卡打开以播放视频时新选项卡的默认图标
- php - 如何在插件内的 wordpress 上创建别名?
- wincc - 激活 WInCC 时缺少 PG/PC 接口
- linux-kernel - 使用 U-Boot 和“sh”启动 Linux 期间的 UART 问题:进程陷阱
- command-line - 列出数字海洋水滴快照以及创建日期
- azure - 如何在 Azure App Service 上实现 Blazor Server 应用程序的租户级关联?
- ssas - Azure 分析服务中的死锁错误