我想在清除搜索字段时隐藏项目,但是当我搜索某个项目并清除搜索字段时,所有项目都将可见。
我尝试过
if(input.value.length == 0){
a[i].style.display = "none";
return;
}else{
a[i].style.display = "block";
}
但这会产生错误:
index.php:160
未捕获的TypeError:无法读取未定义的属性'style'
在filterFunction(index.php:160
)
在HTMLInputElement.onkeyup(index.php:125
)
第125行:<div id="myDropdown" class="dropdown-content">
第160行:filter = input.value.toUpperCase();
这是代码:
<div class="dropdown">
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.."
id="myInput" onkeyup="filterFunction()">
<a href="Index.html">Home</a>
<a href="">Refurbish Desktop</a>
<a href="">Refurbish Laptop</a>
<a href="">Refurbish Monitoren</a>
<a href="">Refurbish Printers</a>
<a href="">Groothandel Desktop</a>
<a href="">Groothandel Laptop</a>
<a href="">Groothandel Monitoren</a>
<a href="">Groothandel Printers</a>
<a href="">Recycling Desktop</a>
<a href="">Recycling Laptop</a>
<a href="">Recycling Thin Client</a>
<a href="">Recycling Monitoren</a>
<a href="">Recycling Printers</a>
<a href="">Werkproces HP Folio 9470m</a>
<a href="">QA Refurbish Desktop</a>
<a href="">QA Refurbish Laptop</a>
<a href="">QA Refurbish Monitoren</a>
<a href="">QA Refurbish Printers</a>
</div>
</div>
<script>
function filterFunction() {
var input, filter, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
if(input.value.length == 0){
a[i].style.display = "none";
return;
}else{
a[i].style.display = "block";
}
for (i = 0; i < a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "block";
} else {
a[i].style.display = "none";
}
}
}
</script>
我希望在清除字段时将其清除
答案 0 :(得分:0)
您没有第一次定义i
尝试一下:
if(input.value.length == 0){
for(i=0;i<a.length;i++){
a[i].style.display = "none";
}
return;
}
else{
for(i=0;i<a.length;i++){
a[i].style.display = "block";
}
}
答案 1 :(得分:0)
您在输入代码上使用onkeyup
事件。您可以尝试用onkeydown
代替onkeyup
吗?
<input type="text" placeholder="Search.." id="myInput" onkeydown="filterFunction()">