我的json数据结构:
var data = {
"FolderList": [
{
"FolderID": 1,
"FolderName": "parent1",
"ParentFolderID": -1
},
{
"FolderID": 2,
"FolderName": "parent1 Child1",
"ParentFolderID": 1
},
{
"FolderID": 3,
"FolderName": "parent2",
"ParentFolderID": -1
},
{
"FolderID": 4,
"FolderName": "parent1 Child1 Child1",
"ParentFolderID": 2
},
{
"FolderID": 5,
"FolderName": "parent1 Child1 Child2",
"ParentFolderID": 2
},
{
"FolderID": 6,
"FolderName": "parent2 Child1",
"ParentFolderID": 3
}
]
};
现在,我想像这样创建文件夹层次结构 html:
parent1
parent1 child1
parent1 child1 child1
parent1 child1 child2
parent2
parent2 child1
其实我想生成这样的HTML代码
<ul> <li>Parent1 <ul> <li>parent1 child1 <ul> <li>parent1 child1 child1</li> <li>parent1 child1 child2</li> </ul> </li> </ul> </li> <li>parent2 <ul> <li>parent2 child1</li> </ul> </li> </ul>
如何使用 JavaScript 或 jQuery 做到这一点?提前致谢。我尝试使用递归函数,但被卡在了中间。但是我的代码是这样的:
function populatedata() {
$.each(data.FolderList, function (i, folder) {
if (folder.ParentFolderID == -1) {
html += '<li>' + folder.FolderName;
checkChild(folder.FolderID);
html += '</li>';
}
});
}
function checkChild(parentid) {
$.each(data.FolderList, function (i, folder) {
if (folder.ParentFolderID == parentid) {
html += '<li><ul>' + folder.FolderName;
checkChild(folder.FolderID);
html+=</ul></li>
return html;
}
else {
return ;
}
});
}
最后在 FAngel 的帮助下使用下面的代码,我创建了项目中实际需要的所需结构
我修改后的代码是这样的:
function populatedata() { var list = $("<ul>").attr({ class: "collapsibleList", id: "folder" }); $.each(data.FolderList, function (i, folder) { if (folder.ParentFolderID == -1) { var item = $("<li>"). css("border-top","0").html('<span>'+folder.FolderName +'</span><a href="Docs.html"> <div class="view-docs pull-right">View</div></a>'); list.append(item); var children = $('<ul>'); item.append(children); checkChild(folder.FolderID, children); } }); $('#folderList').append(list); } function checkChild(parentid, parent) { $.each(data.FolderList, function (i, folder) { if (folder.ParentFolderID == parentid) { var item = $("<li>"). html('<span>'+folder.FolderName +'</span><a href="Docs.html"> <div class="view-docs pull-right">View</div></a>'); var children = $('<ul>'); parent.append(item); item.append(children); checkChild(folder.FolderID, children); } else { return; } }); }