使用jquery构建元素层次结构

时间:2014-02-09 21:01:33

标签: javascript jquery

我需要为每个ul设置深度。我做了

$('.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>

但这会使每个ul的深度='1'。我想得到像

这样的东西
1
  2
1
  2

jquery有可能吗?小提琴在这里http://jsfiddle.net/GLjZt/1/

1 个答案:

答案 0 :(得分:2)

索引不会给你你想要的东西,因为它只会告诉你元素在给定元素集中的位置; $(this).index()将始终返回0.您需要根据父ul计算深度:

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