我是一个学习javascript的学生,我正在尝试构建一个搜索函数。
我有多个带有图片的html图形。我用输入和图表来过滤数字。
我试图隐藏与输入中的值不匹配的数字。
但是我有一个已经有css display:none;的数字。
当您搜索这个特定的图形时,它会弹出,但是在输入再次为空之后,该图形将保持可见。
我试图通过使用obj.style.display = ""和obj.style.display = "none"来重置css。但那不管用。
简单地说,我的目标是隐藏一个图形,直到它与输入的值匹配为止,但是如果输入是空的,它应该再次被隐藏。
任何帮助都将不胜感激,谢谢!
// entire code can be found here: https://codepen.io/Yung_n-d/pen/mdwQGqX
//Javascript
function myFunction() {
var input, filter, ul, li, a, i, txtValue, getSpecial;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("background");
li = ul.getElementsByTagName("figure");
getSpecial = document.getElementsByClassName('special');
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("figcaption")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1 ) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
if(filter == 0){
getSpecial.style.display = "";
}
}
}
//HTML
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Zoek workshops.." title="Type in a name">
<div id="background">
<div id="gallery">
<figure class="pic1 4-5 6-8 8-12 12+ Dans">
<a href="workshopPages/dans/index.php">
<img src="media/fotos/gallery/Dans.png" />
<figcaption class="test">Dans</figcaption>
</figure>
<figure class="special" style="display: none;" id="8-12" class="pic10 4-5 6-8 8-12 12+ ckv">
<a href="workshopPages/reeks/index.php">
<img src="media/fotos/gallery/reeks.png" />
<figcaption>Film</figcaption>
</figure>
</div>
</div>发布于 2022-01-24 11:18:32
.indexOf(‘’)将返回0而不是-1;您还应该测试输入的值字段不是空的。
从以下位置更改了一行:
if (txtValue.toUpperCase().indexOf(filter) > -1 ) {To:
if (filter && txtValue.toUpperCase().indexOf(filter) > -1 ) {https://stackoverflow.com/questions/70832254
复制相似问题