【发布时间】:2022-01-26 20:07:28
【问题描述】:
我正在练习使用循环来处理我的 index.html 上的数据。我目前正在尝试过滤一个输入文本字段,它会在用户键入时显示数据并隐藏其余数据。
//adds input elements
let search = document.getElementById('search');
search.addEventListener('keyup', filterNames);
//Grabs information in ul and li
function filterNames (){
let filterValue = document.getElementById('filterNames');
let ul = document.getElementById ('names');
let li = ul.querySelectorAll('li.name-item');
//loop for collection of items
for (let i = 0; i < li.length; i++) {
let a = li[i].getElementByTagName('a') [0];
// if statement for loop
if (a.innerHTML.toUpperCase().indexOf(filterValue) > -1){
li[i].style.display=' ';
} else {
li[i].style.display='none';
}
}
}
<div class="wrapper">
<input type="text" id="search" placeholder="Search Name...">
<ul class="game-characters" id="names">
<li class="Mario"><a href="#"><h3>Mario</h3></a></li>
<li class="Link"><a href="#"><h3>Link</h3></a></li></li>
<li class="Zelda"><a href="#"><h3>Zelda</h3></a></li></li>
<li class="Bowser"><a href="#"><h3>Bowser</h3></a></li></li>
<li class="Kratos"><a href="#"><h3>Kratos</h3></a></li></li>
<li class="Yoshi"><a href="#"><h3>Yoshi</h3></a></li></li>
</ul>
</div>
【问题讨论】:
-
您正在尝试选择一个 id 为“filterNames”的元素和
li类为“name-item”的元素,但 id/class 不存在于您的 HTML 中。请检查您的代码是否遗漏任何内容。 -
1.
let filterValue = document.getElementById('filterNames')必须是search.value2. 您需要与的 innerText 进行比较 3.
- 没有您要查找的类
-
操作方法如下:jsfiddle.net/3kg2xf0c
标签: javascript list for-loop if-statement