使用JSON和jquery创建嵌套列表 [英] Creating nested list using JSON and jquery
本文介绍了使用JSON和jquery创建嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的JSON,HTML和jquery代码的示例: 杰森:
Hi Below is the sample of my JSON ,HTML and jquery code : Json:
{
"node":[
{"name":"XXX",
"child":[ {"name":"acb"},
{"name":"txy"}
]
},
{"name":"ZZZ",
"child":[{"name":"ism"},
{"name":"sss"}
]
},
{"name":"PPP"},
{"name":"QQQ"}
]
}
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);
}
}
}
因此,当我运行此代码时,列表返回为
So when i am running this code, list is returning as
<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>
请让我如何修改我的函数以这种方式实现嵌套列表!
Please let me how can i modify my function to achieve nested list in this way !.. Thanks in advance .
推荐答案
尝试
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)
}
}
演示:小提琴
这篇关于使用JSON和jquery创建嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文