我想知道是否有一种内置方法可以将像下面这样的JSON转换为带有ul和li的树。
示例JSON:
{
{parent=-1,id=0,name='root'},
{parent=0,id=1,name='x'},
{parent=0,id=2,name='y'},
{parent=1,id=3,name='z'},
{parent=1,id=4,name='w'},
{parent=1,id=5,name='c'},
{parent=2,id=6,name='d'}
}
答案 0 :(得分:2)
这是一个我故意留下无法解释的功能。
function buildNestedList(treeNodes, rootId) {
var nodesByParent = {};
$.each(treeNodes, function(i, node) {
if (!(node.parent in nodesByParent)) nodesByParent[node.parent] = [];
nodesByParent[node.parent].push(node);
});
function buildTree(children) {
var $container = $("<ul>");
if (!children) return;
$.each(children, function(i, child) {
$("<li>", {text: child.name})
.appendTo($container)
.append( buildTree(nodesByParent[child.id]) );
});
return $container;
}
return buildTree(nodesByParent[rootId]);
}
它变成了这个
var treeNodes = [
{parent:-1,id:0,name:'root'},
{parent:0,id:1,name:'x'},
{parent:0,id:2,name:'y'},
{parent:1,id:3,name:'z'},
{parent:1,id:4,name:'w'},
{parent:1,id:5,name:'c'},
{parent:2,id:6,name:'d'}
];
进入这个
<ul>
<li>x
<ul>
<li>z</li>
<li>w</li>
<li>c</li>
</ul>
</li>
<li>y
<ul>
<li>d</li>
</ul>
</li>
</ul>
答案 1 :(得分:0)
您可以在上述<li>
中添加 Hyperlink ,并在上述内部函数的一行中进行以下更改:
$("<li><a href ='#'>"+child.name+"</>", {text: child.name})