Javascript 如果ul里面没有li,我怎么能把它藏起来?
让我们假设我有这个HTML:Javascript 如果ul里面没有li,我怎么能把它藏起来?,javascript,jquery,html,Javascript,Jquery,Html,让我们假设我有这个HTML: <ul class="nested"> <li>text</li> <li>text</li> <li>text</li> </ul> <ul class="nested"> </ul> <ul class="nested"> <li>text</li> <li&
<ul class="nested">
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
<ul class="nested">
</ul>
<ul class="nested">
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
- 正文
- 正文
- 正文
- 正文
- 正文
- 正文
我想检查哪个ul没有li,当页面加载时,并隐藏它
也可以使用jquery来完成
谢谢,您只需要CSS
:empty伪选择器将选择包含以下内容之一的元素:
没有或只有HTML注释
Source要通过jQuery实现这一点,您可以使用
$。jQuery中的每个
…还有许多可能的选项可以解决此问题
$(“.nested”)。每个(函数(索引){
if(!$(this.find(“li”).length){
$(this.hide();
}
});代码>
- 正文
- 正文
- 正文
- 正文
- 正文
- 正文
您可以使用以下jQuery来完成此操作
window.onload = function(){ // When the page has finished loading.
$(".nested").each(function(){ // Check every "nested" class
if($(this).children().length == 0){ // If this nested class has no children
$(this).hide(); // This will hide it, but not alter the layout
// $(this).css("display", "none"); // This will alter the layout
} else{
$(this).show();
//$(this).css("display", "none"); // This will alter the layout
}
}
}
或者,正如用户Rory McCrossan所建议的,写得简单得多:
window.onload = function(){
$('.nested:not(:has(li))').hide(); // Will not alter layout
// $('.nested:not(:has(li))').css("display", "none"); // Will alter layout
}
值得注意的是,所讨论的
包含空格,而:empty
选择器将不匹配空格。是的,不幸的是,如果ul
标记有任何内容,即使是空格,它也不会匹配:empty选择器或仅仅是$('.nested:not(:has(li))。hide()
@RoryMcCrossan,这是一个不可思议的解决方案。和往常一样,印象深刻。简单多了。好多了。
window.onload = function(){
$('.nested:not(:has(li))').hide(); // Will not alter layout
// $('.nested:not(:has(li))').css("display", "none"); // Will alter layout
}