使用JSON和jquery创建嵌套列表

abh*_*ngh 0 html jquery json html-lists

嗨下面是我的JSON,HTML和jquery代码示例:Json:

{
"node":[
{"name":"XXX",
 "child":[ {"name":"acb"},
 {"name":"txy"}
 ]
},
{"name":"ZZZ",
 "child":[{"name":"ism"},
 {"name":"sss"}
 ]
},
{"name":"PPP"},
{"name":"QQQ"}
]
} 
Run Code Online (Sandbox Code Playgroud)

Jquery代码:

$(document).ready(function(){
            var $ul=$('<ul></ul>');
            $.getJSON('test1.json', function(json) {
                    $.each(json.node, function(key,value){
                            getList(value, $ul);
                                               })
                                            });
            $ul.appendTo("body");
                           });
                       function getList(item, $list) {

    if (item) {
        if (item.name) {
            $list.append($('<li><a href="#">' + item.name + '</a>' +"</li>"));
              }
        if (item.child && item.child.length) {
            var $sublist = $("<ul/>");
            $.each(item.child, function (key, value) {
                getList(value, $sublist);
            });
            $list.append($sublist);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,当我运行此代码时,列表将返回为

<ul>
<li></li>
<ul>
<li></li>
<li></li>
</ul>
</ul> .. and so on . But i don't want my list to be this was i need it like :

<ul>
<li>
<ul>
<li></li>
<li></li>
</ul>
</li>
<li>
<ul>
<li></li>
</ul>
</li>
</ul> 
Run Code Online (Sandbox Code Playgroud)

请让我如何修改我的功能,以这种方式实现嵌套列表!..提前谢谢.

Aru*_*hny 5

尝试

function getList(item, $list) {

    if($.isArray(item)){
        $.each(item, function (key, value) {
            getList(value, $list);
        });
        return;
    }

    if (item) {
        var $li = $('<li />');
        if (item.name) {
            $li.append($('<a href="#">' + item.name + '</a>'));
        }
        if (item.child && item.child.length) {
            var $sublist = $("<ul/>");
            getList(item.child, $sublist)
            $li.append($sublist);
        }
        $list.append($li)
    }
}
Run Code Online (Sandbox Code Playgroud)

演示:小提琴