javascript - 搜索栏:包含在列表项标签中的锚标签不可选择
问题描述
我有一个类似于谷歌搜索栏的搜索栏,当您在文本框中输入时,它会根据用户输入提供建议。它过滤包含在无序列表中的一堆项目,并在下面运行 myFunction() 以解析无序列表并显示项目。唯一的问题是,当您单击搜索栏中显示的项目时,链接重定向不起作用,我认为这是因为 onMouseButtonUp 事件没有在列表项上注册(因为当我单击并按住按下按钮,如果有意义的话,它会使项目消失)......想法?
<input style="border-radius: 7px 0px 0px 7px; border-right: 0px; resize: none" id="myInput" onkeyup="myFunction()" name="searchedItem" rows="1" class="form-control" form="searchForm" placeholder="What can we help you find?">
<ul id=myUL>
<li><a href="http://127.0.0.1:8000/products/{{ obj.productName }}">{{obj.productName}}</a></li>
</ul>
<script>
var UL = document.getElementById("myUL");
// hilde the list by default
UL.style.display = "none";
var searchBox = document.getElementById("myInput");
// show the list when the input receive focus
searchBox.addEventListener("focus", function(){
// UL.style.display = "block";
});
// hide the list when the input receive focus
searchBox.addEventListener("blur", function(){
UL.style.display = "none";
});
function myFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
ul = document.getElementById("myUL");
filter = input.value.toUpperCase();
// if the input is empty hide the list
if(filter.trim().length < 1) {
ul.style.display = "none";
return false;
} else {
ul.style.display = "block";
}
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
// This is when you want to find words that contain the search string
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
<!--// This is when you want to find words that start the search string
/*if (a.innerHTML.toUpperCase().startsWith(filter)) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}*/-->
}
}
</script>
解决方案
推荐阅读
- javascript - React 中用于引导和 css 模块的模板文字
- c# - .NET Core 3.1 控制台应用程序作为 Windows 服务
- sql-server - 循环 XML 数据
- jquery - 按钮上的toggleClass动态Jquery
- docker - 为什么 nginx 没有在 Windows Server 2019 docker 容器中启动?
- javascript - jQuery Ajax 多次提交表单
- flutter - 将 Row 固定到其他 UI 小部件顶部的 Scroll View 底部
- ruby - 在运行时将类添加到 ruby 模块
- typescript - 使用 ReturnType<> 时如何使属性可选
- google-maps - 如何使用矩形或多边形从给定区域的谷歌地图获取街道总数