gpt4 book ai didi

javascript - 文本框为空时隐藏元素

转载 作者:行者123 更新时间:2023-12-03 23:01:19 24 4
gpt4 key购买 nike

我无法隐藏 myUL li如果文本框为空,则为元素。有任何想法吗?提前致谢。

<input type="text" id="myInput" onKeyUp="myFunction()" placeholder="Just begin typing.." title="Detail Index">
<ul id="myUL">
<li><a href="/year/2000.html" target="_blank">2000</a></li>
<li><a href="/year/2001.html" target="_blank">2001</a></li>
<li><a href="/year/2002.html" target="_blank">2002</a></li>
</ul>
<script>
function myFunction() {
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
</script>

最佳答案

要在输入为空时隐藏元素,您可以包含 filter if 中的值检查用户是否输入了值的条件。
另请注意,可以通过使用不显眼的事件监听器来改进和简化代码,input事件和一些 ES5 方法:

document.querySelector('#myInput').addEventListener('input', () => {
let filter = document.querySelector('#myInput').value.toUpperCase();
document.querySelectorAll('#myUL li').forEach(el => {
let a = el.querySelector('a'); // gets the first only
el.style.display = filter && (a.textContent || a.innerText).toUpperCase().indexOf(filter) != -1 ? 'list-item' : 'none';
});
});
li { display: none; }
<input type="text" id="myInput" placeholder="Just begin typing.." title="Detail Index">
<ul id="myUL">
<li><a href="/year/2000.html" target="_blank">2000</a></li>
<li><a href="/year/2001.html" target="_blank">2001</a></li>
<li><a href="/year/2002.html" target="_blank">2002</a></li>
</ul>

关于javascript - 文本框为空时隐藏元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65529644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com