[英]Select all “li” that do NOT contain a “ul” within
I'm building a nested drop down navigation for products and I want to automatically hide any categories that are empty. 我正在为产品构建嵌套的下拉导航,我想自动隐藏任何空白类别。
Unfortunately server side language does not allow efficient way of doing this, so I thought I could output number of products each category has directly, then use jQuery to remove any empty nodes. 不幸的是,服务器端语言不允许执行此操作的有效方法,因此我认为我可以直接输出每个类别具有的产品数量,然后使用jQuery删除任何空节点。
I want to target only the li
's within nav#top_nav
: 我只想定位
nav#top_nav
的li
:
<nav id="top_nav">
<nav class="nav1">
<ul>
<li data-num-products="0">
<a href="...">AAA</a>
<ul>
<li data-num-products="3"><a href="...">BBB</a></li>
<li data-num-products="0"><a href="...">CCC</a></li>
</ul>
</li>
<li data-num-products="7"><a href="">DDD</a></li>
</ul>
<nav>
</nav>
Given 1 level of nesting ul
's, I want to remove any li
's that... 给定1个嵌套
ul
的级别,我要删除任何li
那个...
have no nested ul
's within them and 其中没有嵌套
ul
,并且
have data-num-products == 0
. 有
data-num-products == 0
。
So in the example above AAA
is retained because it has ul
children, but CCC
is removed because it has no ul
children and no products. 因此,在上面的示例中,保留了
AAA
,因为它具有ul
子代,但是删除了CCC
,因为它没有ul
子代且没有产品。
UPDATE: 更新:
It might require 2 passes of removal because if a li contains a ul whose li elements are all removed, then we'll want to remove the ul too. 它可能需要2次删除,因为如果li包含一个ul,而所有li元素都已删除,那么我们也将希望删除ul。
$( "#top_nav li").filter( function(){
return !this.getElementsByTagName("ul").length && !+this.getAttribute("data-num-products");
}).remove();
http://jsfiddle.net/X2D7y/ http://jsfiddle.net/X2D7y/
This will only remove if there are no UL descendants AND have attribute value of 0 仅当没有UL后代且属性值为0时才会删除
Like this: 像这样:
$('#top_nav li[data-num-products="0"]:not(:has(ul))').remove();
The selector breakdown is... 选择器故障是...
'#top_nav' // start at element with "top_nav" id
' ' // and select descendant...
'li' // li elements...
'[data-num-products="0"]' // ...where attribute "data-num-products" is "0"
':not(' // ...but exclude li elements that...
':has(ul)' // ...have descendant ul elements
')'
Regarding your updated question, just change :not(:has(ul))
to :not(:has(li))
. 关于更新的问题,只需将
:not(:has(ul))
更改为:not(:has(li))
。
$('#top_nav li[data-num-products="0"]:not(:has(li))').remove();
$("#top_nav li[data-num-products='0']").filter(function() {
return $(this).children("ul").length === 0;
}).remove();
In Javascript: 用Javascript:
var lis = document.querySelectorAll( '#top_nav li[data-num-products="0"]' );
for( var li = 0; li < lis.length; li++ ) {
!lis[li].getElementsByTagName( 'ul' ).length && lis[li].parentNode.removeChild( lis[li] );
};
Demo: http://jsfiddle.net/ThinkingStiff/2zS9B/ 演示: http : //jsfiddle.net/ThinkingStiff/2zS9B/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.