[英]Select all “li” that do NOT contain a “ul” within
我正在為產品構建嵌套的下拉導航,我想自動隱藏任何空白類別。
不幸的是,服務器端語言不允許執行此操作的有效方法,因此我認為我可以直接輸出每個類別具有的產品數量,然后使用jQuery刪除任何空節點。
我只想定位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>
給定1個嵌套ul
的級別,我要刪除任何li
那個...
其中沒有嵌套ul
,並且
有data-num-products == 0
。
因此,在上面的示例中,保留了AAA
,因為它具有ul
子代,但是刪除了CCC
,因為它沒有ul
子代且沒有產品。
更新:
它可能需要2次刪除,因為如果li包含一個ul,而所有li元素都已刪除,那么我們也將希望刪除ul。
$( "#top_nav li").filter( function(){
return !this.getElementsByTagName("ul").length && !+this.getAttribute("data-num-products");
}).remove();
僅當沒有UL后代且屬性值為0時才會刪除
像這樣:
$('#top_nav li[data-num-products="0"]:not(:has(ul))').remove();
選擇器故障是...
'#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
')'
關於更新的問題,只需將: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();
用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] );
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.