我需要根据 parent_id 添加深度类。
json数据:
[
{"id":1,"name":"one","parent_id":0},
{"id":2,"name":"two","parent_id":0},
{"id":3,"name":"three","parent_id":0},
{"id":4,"name":"four","parent_id":0},
{"id":5,"name":"five","parent_id":0},
{"id":6,"name":"one","parent_id":2},
{"id":7,"name":"two","parent_id":6},
{"id":8,"name":"three","parent_id":6},
{"id":9,"name":"four","parent_id":8},
{"id":10,"name":"five","parent_id":8},
]
结果应该是:
<ul class="menu">
<li class="depth-0 menu-item-1"><li>
<li class="depth-0 menu-item-2"><li>
<li class="depth-1 menu-item-6"><li>
<li class="depth-2 menu-item-8"><li>
<li class="depth-3 menu-item-9"><li>
<li class="depth-3 menu-item-10"><li>
<li class="depth-2 menu-item-7"><li>
<li class="depth-0 menu-item-3"><li>
<li class="depth-0 menu-item-4"><li>
<li class="depth-0 menu-item-5"><li>
</ul>
我努力了
$.each(data, function(i, item) {
if(item.parent_id > 0){
$(this).addClass('depth-1');
}
});
如果 itemparent_id
是0
then class 应该是depth-0
if item has parent_id
(child item)
then class should be depth-1
and if has (sub child item)
depth-2
。任何人都可以指导我如何做到这一点?