嗨,我想算一下没有UL的L1,只有第一级,
但是当我算这个时,它显示大小4而不是2,它也计数内部的李.
但是当我算这个时,它显示大小4而不是2,它也计数内部的李.
<div class="navigation-container"> <ul class="first-level"> <li><a href="#">Link 1</a></li> <li><a href="#">Link 2</a> <ul> <li><a href="#">Link2.1</a></li> <li><a href="#">Link2.2</a> <ul> <li><a href="#">Link 2.2.1</a></li> </ul> </li> </ul> </li> <li><a href="#">Link </a></li> </ul> </div>
jQuery为此.
jQuery(document).ready(function(){ var nosubnav = jQuery('.first-level li:not(:has(ul))'); var nosubnavsize = jQuery('.first-level li:not(:has(ul))').size(); jQuery(nosubnav).css('border','1px solid red'); alert('List item which does not have submenu '+nosubnavsize); });
谢谢
解决方法
您可以使用子选择器>只能直接在父级别下面定位子元素.
jQuery(document).ready(function(){ var nosubnav = jQuery('.first-level > li:not(:has(ul))'); var nosubnavsize = jQuery('.first-level > li:not(:has(ul))').size(); jQuery(nosubnav).css('border','1px solid red'); alert('List item which does not have submenu '+nosubnavsize); });
这将返回2的计数.您还可以通过重新使用存储的目标li(存储在nosubnav中)的选择来稍微优化:
jQuery(document).ready(function(){ var nosubnav = jQuery('.first-level > li:not(:has(ul))'); nosubnav.css('border','1px solid red'); alert('List item which does not have submenu '+nosubnav.length); });