[置顶] 后台传的json串页面生成树

时间:2021-11-28 12:01:16
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<style type="text/css">
body{
font-size:14px;
margin:0;}
div{
width:auto;
height:auto;
line-height:150%;}
ul{
list-style:none;
margin-left:-20px;}
ul li:hover{
background-color:#DDDDDD;
color:#FF0000;
cursor:pointer;}
</style>
</head>

<body>
<div id="continer"></div>
</body>
</html>
<script language="javascript" src="jquery-1.10.2.min.js"></script>
<script language="javascript">
//模拟数据
var jsonData =
[{"subnetId":1,"subnetNode":-1,"subnetRemark":"状态自带","subnetName":"中心网络"},
{"subnetId":2,"subnetNode":1,"subnetRemark":"好好的","subnetName":"北京"},
{"subnetId":3,"subnetNode":1,"subnetRemark":"大唐电信","subnetName":"大唐电信"},
{"subnetId":4,"subnetNode":1,"subnetRemark":"","subnetName":"上海"},
{"subnetId":5,"subnetNode":4,"subnetRemark":"","subnetName":"中国联通"},
{"subnetId":6,"subnetNode":3,"subnetRemark":"","subnetName":"移动"},
{"subnetId":7,"subnetNode":2,"subnetRemark":"","subnetName":"你好"}];

//主方法,运用递归实现
function createTree(jsons,subnetNode){
if(jsons != null){
var ul = '<ul class="">' ;
for(var i=0;i<jsons.length;i++){
if(jsons[i].subnetNode == subnetNode){
ul += '<li>' + jsons[i].subnetName + "</li>" ;
ul += createTree(jsons,jsons[i].subnetId) ;
}
}
ul += "</ul>" ;
}
return ul ;
}

$(function(){
var ul = createTree(jsonData,-1) ;

$("#continer").append(ul) ;

//控制菜单的隐藏显示
$("ul[class] li").each(function(){
$(this).click(function(){
$(this).next().toggle() ;
}) ;
}) ;

}) ;

</script>