这个需要运用递归。
案例:将数据以 ul li ul li形式展现在div中。
<div id="div"></div>
数据格式为json:
var data=[
{id:1, name:"信息1",
children :[{id:1, name:"信息1-1-1"},{id:1, name:"信息1-1-2",
children :[{id:1, name:"信息1-2-1"},{id:1, name:"信息1-2-2",
children :[{id:1, name:"信息1-3-1"},{id:1, name:"信息1-3-2"}]
}]
}]
},
{id:1, name:"信息2",
children :[{id:1, name:"信息2-1-1"},{id:1, name:"信息2-1-2",
children :[{id:1, name:"信息2-2-1"},{id:1, name:"信息2-2-2"}]
}]
}
];
函数:
function nodeHtml(data){
if(data.length > 0){
var _html = '<ul>';
for(var key in data) {
_html += '<li id="'+ data[key]['id'] +'">'+ data[key]['name'] +'</li>';
if(data[key]['children'] != undefined){
_html += nodeHtml(data[key]['children']);
}
}
_html += '</ul>';
return _html;
}
}
最后:
var html = nodeHtml(data);
$('#div').html(html);
显示样式: