Javascript 在清除输入时隐藏列表项
我一直在寻找我问题的答案,但找不到任何特别的答案,所以我会在这里提问。我的问题是,当我清除输入字段时,我所有的列表项都会显示在屏幕上,它们不应该可见,因为它们被设置为显示:无,直到在搜索字段中输入了一个字母。这是我的JS代码,并将提供一个指向glitch的链接,以便您可以在需要时查看项目。我是javascript新手,所以如果这是一个愚蠢的问题,请不要对我苛刻:D提前谢谢Javascript 在清除输入时隐藏列表项,javascript,list,Javascript,List,我一直在寻找我问题的答案,但找不到任何特别的答案,所以我会在这里提问。我的问题是,当我清除输入字段时,我所有的列表项都会显示在屏幕上,它们不应该可见,因为它们被设置为显示:无,直到在搜索字段中输入了一个字母。这是我的JS代码,并将提供一个指向glitch的链接,以便您可以在需要时查看项目。我是javascript新手,所以如果这是一个愚蠢的问题,请不要对我苛刻:D提前谢谢 //Get the input element let filterInput = document.getEleme
//Get the input element
let filterInput = document.getElementById("searchInput");
//Add event listener
filterInput.addEventListener("keyup", filterNames);
function filterNames(){
//Get the value of the input
let filterValue = document.getElementById("searchInput").value.toUpperCase();
//Get the names unordered list
let ul = document.getElementById("names");
//Get the list items
let li = ul.querySelectorAll("li.collection-item");
let h = ul.querySelectorAll("li.collection-header");
//Loop trough the collection
for(let i=0; i < li.length; i++){
let a = li[i].getElementsByTagName("a")[0];
//If matched
if(a.innerHTML.toUpperCase().indexOf(filterValue) > -1 && a.innerHTML.toUpperCase().indexOf(filterValue) === 0){
li[i].style.display = "block";
} else{
li[i].style.display = "";
}
}
for(let i = 0; i < h.length; i++){
let title = h[i].getElementsByTagName("h3")[0];
if(title.innerHTML.toUpperCase().indexOf(filterValue[0]) > -1){
h[i].style.display = "block";
} else {
h[i].style.display = "";
}
};
}
//获取输入元素
让filterInput=document.getElementById(“searchInput”);
//添加事件侦听器
filterInput.addEventListener(“键控”,filterNames);
函数过滤器名称(){
//获取输入的值
让filterValue=document.getElementById(“searchInput”).value.toUpperCase();
//从无序列表中获取名称
设ul=document.getElementById(“名称”);
//获取列表项
设li=ul.queryselectoral(“li.collection项”);
设h=ul.queryselectoral(“li.collection头”);
//在收藏中循环
for(设i=0;i-1&&a.innerHTML.toUpperCase().indexOf(filterValue)==0){
li[i].style.display=“block”;
}否则{
李[i].style.display=“”;
}
}
对于(设i=0;i-1){
h[i].style.display=“block”;
}否则{
h[i].style.display=“”;
}
};
}
这里有一个到glitch项目的链接:尝试添加
let has\u input=filterValue.length>0编码>然后将每个if(…)
更改为if(有输入&&…
)
还可以使用style.display=“无”编码>以隐藏项目。可能是因为要将显示设置为“无”,您不需要编写
.style.display=”“代码>
而是
.style.display=“无”代码>非常感谢!这是我的本意。真的非常感谢你,这让我非常困扰,可能比它应该的要多哈哈,对javascript来说还是很新的:下面的DPeter B提供了答案:D顺便说一句,它的.style.display=“”;设置的目的是让它们停留在display:none,因为我在CSS中将它们设置为display:none,然后在输入时更改display:block:D