HTML:
<div id="container"></div>
CSS:
ul {
margin-left: 20px;
list-style-type: disc;
}
JS:
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'}
];
$("#container").append( buildNestedList(treeNodes, 0) );
Result:
<div id="container"></div>
CSS:
ul {
margin-left: 20px;
list-style-type: disc;
}
JS:
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'}
];
$("#container").append( buildNestedList(treeNodes, 0) );
Result:
- x
- z
- w
- c
- y
- d
No comments:
Post a Comment