js怎样将获取json转换为树形结构
比如这样一段json
{
"name": "1级菜单1",
"link": "###",
"isleaf": false,
"level": 0,
"children": [
{
"name": "2级菜单1",
"link": "###",
"isleaf": false,
"level": 1,
"children": [
{
"name": "3级菜单1",
"link": "###",
"isleaf": true,
"level": 2,
"children": null
},
{
"name": "3级菜单2",
"link": "###",
"isleaf": true,
"level": 2,
"children": null
}
]
},
{
"name": "2级菜单2",
"link": "###",
"isleaf": false,
"level": 1,
"children": [
{
"name": "3级菜单3",
"link": "###",
"isleaf": true,
"level": 2,
"children": null
}
]
}
]
}
我怎样把他转换成
<div>
<a href="###">一级菜单</a>
<ul>
<li>
<a>2级菜单1</a>
<ul>
<li><a href="###">3级菜单1</a></li>
<li><a href="###">3级菜单2</a></li>
</ul>
</li>
<li>
<a href="###">2级菜单2</a>
.......
</li>
</ul>
</div>
hjj123
9 years, 8 months ago
Answers
建议下载个jQuery EASYUI的API里面有关于树的解释,很清楚的
http://www.cnblogs.com/Philoo/archive/2011/11/17/jeasyui_api_index.htm...
树荫里的大象
answered 9 years, 8 months ago
targetA
answered 9 years, 8 months ago
下面的代码
render
是主函数,用来render你提供的
json
数据,它调用了
renderMenu
函数。
javascript
function renderMenu(menu, parent) { var el = $('<a href="' + menu.link +'">' + menu.name + '</a>'); $(parent).append(el); if (menu.isleaf) { return parent; } var ul = $('<ul/>'); for (var i = 0; i < menu.children.length; ++i) { var li = $('<li/>'); renderMenu(menu.children[i], li); ul.append(li); } $(parent).append(ul); return parent; } function render(json) { var div = $(' <div/> '); return renderMenu(json, div); } var json = // 你的那段json代码 var menu = render(json);
在浏览器中检查menu显示如下:
如果您觉得回答有帮助,就点个赞呗:-)
mj1986
answered 9 years, 8 months ago