清除搜索输入字段后,如何从搜索过滤器中隐藏列表项? [英] How to hide the List items from Search Filter, when search input field is cleared?
问题描述
我有一个HTML列表项,如下所示:
I have a HTML list items like this:
<ul id="fruits">
<li><a href="#">Mango</a></li>
<li><a href="#">Apple</a></li>
<li><a href="#">Grape</a></li>
<li><a href="#">Cherry</a></li>
</ul>
用户将看不到这些项目,因为我们将所有样式隐藏为display: none;
.
用户可以从input
字段下方搜索这些项目:
User will not see these items, as we are hiding them all with style display: none;
.
User can search these items from below input
field:
<input type="text" id="searchInput" onkeyup="fruitSearch()" placeholder="Search fruits">
当用户开始在input
字段上搜索水果名称时,它将列出匹配的名称,就像google搜索建议一样.
使用下面的JavaScript进行搜索:
When user start searching for a fruit name on the input
field, it will list the matching names, just like google search suggestions.
using the below the JavaScript for search:
function fruitSearch() {
// Declare variables
var input, filter, ul, li, a, i;
input = document.getElementById('searchInput');
filter = input.value.toUpperCase();
ul = document.getElementById("fruits");
li = ul.getElementsByTagName('li');
// Loop through all list items, and show those who match the search query
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "block";
} else {
li[i].style.display = "none";
}
}
}
一切工作均按设计&直到此为止,除非用户清除输入字段,否则所有水果列表项<li>
现在都可见而不是隐藏.
Everything is working as designed & expected until here, once the user clears the input field all the fruit list items <li>
are visible now instead of hiding.
如何重置列表项和当用户清除input
字段时将其全部隐藏?
How do I reset the list items & hide them all, when user clears the input
field?
https://jsfiddle.net/kingBethal/cjbwomof/
推荐答案
首先,您需要更改html.您需要在<li>
标记内添加<a>
,因为在您的JavaScript代码中,您是从<a>
元素获取内容的.
Firstly you need to change your html. You need to add <a>
inside your <li>
tags because in your javascript code your get content from <a>
element.
<ul id="fruits">
<li><a href="#">Mango</a></li>
<li><a href="#">Apple</a></li>
<li><a href="#">Grape</a></li>
<li><a href="#">Cherry</a></li>
</ul>
然后您可以创建一个条件来检查输入的长度是否大于一个
Then you can make a condition to check if length of input is more than one
function fruitSearch() {
// Declare variables
var input, filter, ul, li, a, i;
input = document.getElementById('searchInput');
filter = input.value.toUpperCase();
ul = document.getElementById("fruits");
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) > -1) {
li[i].style.display = "block";
} else {
li[i].style.display = "none";
}
}
}
您在这里工作了 jsfiddle
这篇关于清除搜索输入字段后,如何从搜索过滤器中隐藏列表项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!