我无法隐藏 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/