2014-02-09 75 views
1

我需要爲每個ul設置較深的元素。我做使用jquery創建元素層次結構

$('.topnav').find('ul').each(function(){ 
    $(this).attr('deep', $(this).index()); 
}) 

HTML

<ul class="topnav dropdown" > 
    <li class="expand"> 
     <a href="/posluhy">Top</a> 
     <ul class="subnav"> 
      <li class="expand"> 
       <a href="/posluhy/metalocherepycja">Sub cat 1</a> 
       <ul class="subnav"> 
        <li > 
         <a href="/posluhy/metalocherepycja/dsafsadf">Sub Sub cat 1</a> 
        </li> 
       </ul> 
      </li> 
      <li class="expand"> 
       <a href="/posluhy/metalocherepycja">Sub cat 2</a> 
       <ul class="subnav"> 
        <li > 
         <a href="/posluhy/metalocherepycja/dsafsadf">Sub Sub cat 2</a> 
        </li> 
       </ul> 
      </li> 
     </ul> 
    </li> 
</ul> 

但這使深= '1',每個UL。我想得到像

1 
    2 
1 
    2 

這可能與jQuery的?小提琴在這裏http://jsfiddle.net/GLjZt/1/

+0

使用'數據 - *'屬性,而不是過時的自定義屬性。 –

回答

2

索引不會給你你想要的,因爲它只會告訴你元素在給定的元素集內的位置; $(this).index()將始終返回0。你需要基於父ul的計算深度:

$('.topnav').find('ul').each(function(){ 
    $(this).attr('deep', $(this).parents('ul').length);//set attr deep 
}) 
+0

不起作用http://jsfiddle.net/GLjZt/2/,深未設置 –