Skip to content

Instantly share code, notes, and snippets.

@oakhole
Last active August 29, 2015 14:01
Show Gist options
  • Save oakhole/6fb820877dc41579bdfe to your computer and use it in GitHub Desktop.
Save oakhole/6fb820877dc41579bdfe to your computer and use it in GitHub Desktop.
<html>
<head>
<title>simple tree demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function initTree(){
var nodes=[{id:1,name:'a',pid:0},
{id:2,name:'b',pid:1},
{id:3,name:'c',pid:1},
{id:4,name:'d',pid:0},
{id:5,name:'e',pid:2},
{id:6,name:'f',pid:0},
{id:7,name:'g',pid:4},
{id:8,name:'h',pid:5},
{id:9,name:'i',pid:8},
{id:10,name:'j',pid:9}
];
createTree(nodes,nodes.length-1,0);
}
var treeHtml = "";
function createTree(nodes,length,pid){
//递归终止
if(length == -1){
return false;
}
if(nodes[length]["pid"] == pid){
treeHtml = treeHtml + "<li id=" + nodes[length]["id"] + ">" + nodes[length]["name"];
for(i = 0;i< nodes.length; i++){
//判断是否含有子节点,有则进入递归体,否则退出循环;
if(nodes[i]["pid"] == nodes[length]["id"]){
treeHtml = treeHtml + "<ul>";
createTree(nodes,nodes.length-1,nodes[length]["id"]);
treeHtml = treeHtml + "</ul>";
break;
}
}
treeHtml = treeHtml + "</li>";
}
createTree(nodes,length-1,pid);
}
$(function(){
initTree();
$("#treeDemo").html(treeHtml);
});
</script>
</head>
<body>
<div style="background:red;">
<ul id="treeDemo">
</ul>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment