Creating a nested list using JSON and jquery
Hi Below is an example 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 code:
$(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 run this code the list is returned 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 give me how I can change my function to achieve a nested list in this way! .. Thanks in advance.
0
source to share
1 answer
Try
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)
}
}
Demo: Fiddle
+4
source to share