the*_*ing 2 html javascript jquery html5
我有这样的HTML列表项:
<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>
Run Code Online (Sandbox Code Playgroud)
用户不会看到这些项目,因为我们将所有样式都隐藏起来display: none;。用户可以从以下input字段搜索这些项目:
<input type="text" id="searchInput" onkeyup="fruitSearch()" placeholder="Search fruits">
Run Code Online (Sandbox Code Playgroud)
当用户开始在input字段上搜索水果名称时,它将列出匹配的名称,就像google搜索建议一样。使用下面的JavaScript进行搜索:
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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
直到这里一切都按设计和预期的方式进行,直到用户清除了输入字段,所有水果列表项<li>现在都可见而不是隐藏。
用户清除input字段后,如何重置列表项并全部隐藏?
首先,您需要更改您的html。您需要<a>在<li>代码内添加代码,因为在JavaScript代码中,您可以从<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>
Run Code Online (Sandbox Code Playgroud)
然后,您可以创建一个条件来检查输入的长度是否大于一个
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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,您可以使用jsfiddle
| 归档时间: |
|
| 查看次数: |
3186 次 |
| 最近记录: |