将JSON转换为HTML树 [英] Convert JSON to HTML Tree
本文介绍了将JSON转换为HTML树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从下面的JSON示例生成一个HTML树(最好是UL-LI)。有没有人能够处理这种特定结构的简单,递归JS函数(不是框架)?感谢您的帮助!
I would like to generate an HTML tree (preferably UL-LI) from the JSON example below. Does anyone have a simple, recursive JS function (not a framework) that can handle this specific structure? Thanks for your help!
{ "folder" : [ {
"title" : "1",
"folder" : [ {
"title" : "1.1",
"folder" : [ {
"title" : "1.1.1",
} , {
"title" : "1.1.2",
} ]
} ]
} , {
"title" : "2",
} ] }
推荐答案
function to_ul (obj) {
// --------v create an <ul> element
var f, li, ul = document.createElement ("ul");
// --v loop through its children
for (f = 0; f < obj.folder.length; f++) {
li = document.createElement ("li");
li.appendChild (document.createTextNode (obj.folder[f].title));
// if the child has a 'folder' prop on its own, call me again
if (obj.folder[f].folder) {
li.appendChild (to_ul (obj.folder[f].folder));
}
ul.appendChild (li);
}
return ul;
}
警告:没有错误检查!如果缺少标题或文件夹,整个事情就会爆发。
Caveat: No error checking! If a 'title' or 'folder' is missing, the whole thing could blow up.
干杯,
这篇关于将JSON转换为HTML树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文