我需要根据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');
}
});
如果项parent_id
为0
,那么如果项目包含depth-0
parent_id
,则类应为(child item)
,那么类应为depth-1
,如果有(sub child item)
depth-2
。任何人都可以指导我怎么做?
答案 0 :(得分:3)
尝试这种方式:
var depths = [];
$.each(data, function(i, item) {
depths[item.id] = (depths[item.parent_id] || 0) + 1;
});
这会给你一个深度数组(从1开始)
所以对于数据
var data = [
{"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},
];
深度数组将是:
[undefined, 1, 1, 1, 1, 1, 2, 3, 3, 4, 4]
即菜单项1的深度为1,菜单项6的深度为2 ......与您的示例类似。
现在迭代深度阵列&amp;生成菜单项......
答案 1 :(得分:1)
实现loxxi的答案你可以这样做:
$.each(data, function(i, item) {
depthsTemp[item.id] = (depthsTemp[item.parent_id] || 0) + 1;
});
depths = $.map(depthsTemp, function(item) {
return --item;
}).splice(1);
function buildList(depthList) {
var html = '<ul class="menu">\n';
for (var i = 0; i < depthList.length; i++) {
html += '<li class="depth-' + depthList[i] + ' menu-item-' + (i + 1) + '"></li>\n';
}
html += '</ul>';
return html;
}
请参阅此<{p>}的working JSFiddle