jQuery实现递归
前⼏天公司做⼀个递归,
是这样⼦的形式:
<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" "/TR/html4/loose.dtd"> <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="//leapis/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",
jquery实现ajax"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作为下⼀个递归遍历的⽗亲节点传⼊
//递归
showall(childlist[child].childlist, $(li).children().eq(1));
}
//如果该节点没有⼦节点,则直接将该节点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>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论