gpt4 book ai didi

javascript - 检测列表是否为空

转载 作者:行者123 更新时间:2023-11-28 18:13:45 25 4
gpt4 key购买 nike

我正在使用w3School's tutorial创建过滤器列表。我想知道是否有一种方法可以检查列表何时为空并执行函数,以及何时列表中有内容并执行函数。是否可以?谢谢。

最佳答案

您可以使用querySelectorAll来获取所有li,然后检查有多少。

if(document.querySelectorAll("#myUL li").length === 0) {
// The list is empty
} else {
// The list is not empty
}

编辑

正如 Punit 注意到的(请参阅此答案的评论),li 元素不会被删除,而是被隐藏。

要在搜索后无论列表是否为空都执行函数,最简单的方法是修改 for 循环以添加一个存储结果数量的变量:

var foundCount = 0;
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
foundCount++; // Increment the count
} else {
li[i].style.display = "none";
}
}

然后测试 foundCount 变量:

if(foundCount === 0) {
// List is empty
} else {
// There is at least one element
}

关于javascript - 检测列表是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41092498/

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