js链接不能在过滤列表项上工作



所以我想让输入字段和列表选项隐藏的过滤列表,所以我发现了一个代码,它有我需要的一切,除了问题,当我从列表中选择一个选项,它不会重定向到链接页面。谁能帮忙更正下面的代码?

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";
}*/
}
}
<h2>My Phonebook</h2>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<ul id="myUL">
<li><a href="www.google.com/">Adele</a></li>
<li><a href="https://www.youtube.com/">Agnes</a></li>
<li><a href="#">Billy</a></li>
<li><a href="#">Bob</a></li>
<li><a href="#">Calvin</a></li>
<li><a href="#">Christina</a></li>
<li><a href="#">Cindy</a></li>
</ul>

// hide the list when the input receive focus
/*searchBox.addEventListener("blur", function(){
UL.style.display = "none";
});*/

单击<ul>时将设置display:none。在URL重定向前设置display:none

另外,当你链接外部链接时,你需要用http://启动它,否则浏览器将其识别为内部链接。

最新更新