javascript 输出树形结构数据

 我来答
ykxkknd6
2011-12-13
知道答主
回答量:36
采纳率:0%
帮助的人:19.2万
展开全部
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
a{
display:block;
cursor:hand;
}

#host{
width:200px;
height:500px;
background-color:#EFFFB4;
}

.menu{
position:relative;left:8%;
}

</style>
</head>
<body>
<div id="host">

</div>
<script type="text/javascript">
var list = [
[0,1,"a",""],[0,2,"b",""],[0,3,"c",""],[1,4,"a1",""],[1,5,"a2","http://www.sina.com"],[2,6,"b1","http://www.sina.com"],[3,7,"c1","http://www.sina.com"],[3,8,"c2","http://www.sina.com"],[3,9,"c3","http://www.sina.com"],[4,10,"a3","http://www.sina.com"]
];
var menu = {};
function initList(list){
if(!list instanceof Array){
return;
}
var host = document.getElementById("host");
for(var i=0,len=list.length;i<len;i++){
var pid = list[i][0];
if(!menu[pid]) menu[pid] = [];
menu[pid].push({
pid : pid,
id : list[i][1],
text : list[i][2],
href : list[i][3]
});
}
var firstList = menu[0];
var tmp = document.createDocumentFragment();
for(var i=0,len=firstList.length;i<len;i++){
var span = document.createElement("a");
span.innerHTML = firstList[i].text;
span.id = firstList[i].id;
span.attachEvent("onclick",function(event){
var target = event.srcElement;
var nextDom = target.nextSibling;
if(nextDom && nextDom.nodeName == 'DIV'){
target.parentNode.removeChild(nextDom);
return;
}
var pid = target.id;
createList(pid,target);
});
tmp.appendChild(span);
}
host.appendChild(tmp);
}

function createList(pid,target){
var div = document.createElement("div");
div.className = "menu";
var list = menu[pid];
if(!list) return;
for(var i=0,len=list.length;i<len;i++){
var span = document.createElement("a");
span.innerHTML = list[i].text;
span.id = list[i].id;
if(list[i].href) span.href = list[i].href;
span.attachEvent("onclick",function(event){
var target = event.srcElement;
var nextDom = target.nextSibling;
if(nextDom && nextDom.nodeName == 'DIV'){
target.parentNode.removeChild(nextDom);
return;
}
var pid = target.id;
createList(pid,target);
});
div.appendChild(span);
}
target.insertAdjacentElement('AfterEnd',div);
}

initList(list);
</script>

</body>
</html>
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式