前几天公司做一个递归,
是这样子的形式:
<ul>
<li><a>测试1</a>
<ul>
<li><a>测试1.1</a></li>
<li><a>测试1.2</a></li>
</ul>
</li>
<li><a>测试2</a></li>
</ul>
用到了json串
源代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
var childlist = {
"childlist" : [ {
"childlist" : [ {
"childlist" : [],
"name" : "t2name",
"pass" : "t2pass"
}, {
"childlist" : [],
"name" : "t1name",
"pass" : "t1pass"
} ],
"name" : "t1name",
"pass" : "t1pass"
}, {
"childlist" : [ {
"childlist" : [ {
"childlist" : [],
"name" : "t1name",
"pass" : "t1pass"
} ],
"name" : "t1name",
"pass" : "t1pass"
}, {
"childlist" : [],
"name" : "t1name",
"pass" : "t1pass"
} ],
"name" : "t4",
"pass" : "t4"
} ],
"name" : "",
"pass" : ""
}
functionshowall(childlist, parent) {
for ( var child in childlist) {
//如果有子节点,则遍历该子节点
if (childlist[child].childlist.length > 0) {
//创建一个子节点a
var la = $("<a></a>");
//创建一个子节点li
var li = $("<li></li>");
$(la).append(childlist[child].name);
//将li的文本设置好,并马上添加一个空白的ul子节点,并且将这个li添加到父亲节点中
$(li).append(la).append("<ul></ul>").appendTo(parent);
//将空白的ul作为下一个递归遍历的父亲节点传入
//递归
}
//如果该节点没有子节点,则直接将该节点li以及文本创建好直接添加到父亲节点中
else {
var la = $("<a></a>");
var li = $("<li></li>");
$(la).append(childlist[child].name);
$(li).append(la).appendTo(parent);
}
}
}
$(document).ready(function() {
$("#ok").click(function() {
var showlist = $("<ul></ul>");
showall(childlist.childlist, showlist);
$("#div_menu").append(showlist);
});
});
</script>
</head>
<body>
<input id="ok" type="button" value="tree">
<br>
<hr>
<div id="div_menu"></div>
</body>
</html>