我正在尝试使用以下JSON数据在递归内部函数中创建以下类似的结构并没有太多运气,真的需要一些帮助,所以如果有人可以协助请做。提前谢谢
代码(编辑):
$('#citytree').html('');
$.ajax({
type: "POST",
url: base_url+"Cprivileges/checkbox",
data: dataString,
dataType: "json",
cache: false,
beforeSend: function(){$('#ajax_loading').show();},
complete:function(){$('#ajax_loading').hide();},
success: function(data){
chebox = "<ul>";
$.each(data.cuy, function(i,cuy){
chebox = chebox + "<li><input type='checkbox' value=" + cuy.idmenu + " name='mk[]'>" + cuy.Title + "</li>";
});
chebox = chebox + "</ul>";
$("#citytree").append(chebox);
}
});
JSON:
{
"cuy": [{
"idmenu": "1",
"IDparent": "0",
"Title": "Data Aktifitas Supporting"
}, {
"idmenu": "2",
"IDparent": "1",
"Title": "Sumber Daya Manusia"
}, {
"idmenu": "3",
"IDparent": "0",
"Title": "Ratio Keuangan"
}, {
"idmenu": "4",
"IDparent": "3",
"Title": "Beban Resiko Operasional"
}, {
"idmenu": "5",
"IDparent": "3",
"Title": "Business Plan"
}]
}
如何生成这个:
答案 0 :(得分:0)
这段code可能有助于实现您的功能;
for (var i = 0; i < json.length; i++) {
console.log(json.length +"...."+json[i].cuy.length);
for (var j=0; j< json[i].cuy.length; j++){
console.log(json[i].cuy[j].Title);
$("#test").append("<ul>"+json[i].cuy[j].Title+"</ul");
}
}
另一个最佳解决方案是使用$.getJSON它可以帮助您解决问题;
答案 1 :(得分:0)
你需要这样的东西:
var ul = $("#container");
for (var i = 0; i < json.cuy.length; i++) {
var txt = "<li data-id='" + json.cuy[i].idmenu + "'>" + json.cuy[i].Title + "</li>";
var parent;
if (json.cuy[i].IDparent === "0") {
parent = ul;
} else {
var $elem = ul.find("li[data-id='" + json.cuy[i].IDparent + "']");
if ($elem.find("ul").length == 0) {
$elem.append("<ul>");
}
parent = $elem.find("ul:first");
}
parent.append(txt);
}
答案 2 :(得分:0)
只要您的数据列表按当前顺序排序,也就是说兄弟节点必须出现在列表中的父节点之后,此解决方案才会起作用:
function buildList(list) {
var html = [],
item, next;
html.push('<ul>');
while (list.length) {
item = list.shift();
next = list[0] || {};
html.push('<li>', item.Title);
if (next.IDparent === item.idmenu) {
html.push(buildList(list));
}
html.push('</li>');
next = list[0] || {};
if (next.IDparent !== item.IDparent) {
break;
}
}
html.push('</ul>');
return html.join('');
}
用法:buildList(data.cuy);
。