0

我需要根据 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_id0then class 应该是depth-0if item has parent_id (child item)then class should be depth-1and if has (sub child item) depth-2。任何人都可以指导我如何做到这一点?

4

2 回答 2

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...类似于您的示例。

现在迭代深度数组并生成菜单项......

于 2013-05-27T16:27:27.673 回答
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;
}

请参阅此工作的JSFiddle

于 2013-05-27T17:06:39.490 回答