gpt4 book ai didi

javascript - 使用 jquery 构建元素层次结构

转载 作者:行者123 更新时间:2023-11-30 17:37:56 25 4
gpt4 key购买 nike

我需要为每个 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 的 deep='1'。我想得到类似的东西

1
2
1
2

jquery 可以吗? fiddle 在这里 http://jsfiddle.net/GLjZt/1/

最佳答案

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

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

关于javascript - 使用 jquery 构建元素层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21664994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com