2013-06-03 22 views
2

我有一個問題,試圖選擇每個錨項目,除了最後ul中的個人。jQuery每個循環從除最後一級以外的所有級別獲得選定的信息

例HTML(簡化versioon)

<div id="foo"> 
<nav> 
    <ul> 
     <li> 
      <a href="#" class="active"><span>xxxxx</span></a> 
      <ul class="level2"> 
       <li> 
        <a href="#"><span>xxxxx</span></a> 
        <ul class="level3"> 
         <li><a href="#"><span>xxxxx</span></a></li> 
         <li><a href="#"><span>xxxxx</span></a></li> 
         <li><a href="#"><span>xxxxx</span></a></li> 
         <li><a href="#"><span>xxxxx</span></a></li> 
        </ul> 
       </li> 
      </ul> 
     </li> 
    </ul> 
</nav> 
</div> 

一些示例性的jQuery我曾嘗試(但失敗並返回所有錨)

var menu = $('#foo'); 
     menu.find("nav ul:not(:last) a").each(function() { 
      console.log($(this).text()); 
     }); 

上述返回從所有示例6個錨。

我只想要2個錨點(前2個水平,而不是最後一個)。

任何指針將不勝感激。

感謝

回答

1

試試這個 -

menu.find("nav ul a").filter(function(){ 
    return $(this).closest('ul').find('ul').length > 0; 
}).each(function() { 
      console.log($(this).text()); 
}); 

演示-->http://jsfiddle.net/a5BeV/

0

,你只需要選擇直接後代的最簡單的方法:

http://jsfiddle.net/PQVPu/

var menu = $('#foo'); 
     menu.find("nav ul:not(:last) > li > a").each(function() { 
      $(this).css('color','red'); 
     }); 
0
menu.find("ul:not(:last) > li > a") 

可能是您正在尋找的選擇器。

相關問題