<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="jquery-3.2.1.js"></script>
<style>
.tree {
}
.tree ul li{
list-style-type:none;
}
.tree a{
cursor:pointer;
}
.tree span{
cursor:pointer;
}
</style>
</head>
<body>
<div id='treedemo' class='tree'>
</div>
<script>
var data = [
{
id:1,
city:'云南省',
child:[
{
id:2,
city:'昆明市',
child:[
{id:3,city:'五华区',child:[]},
{id:4,city:'盘龙区',child:[]},
{id:5,city:'官渡区',child:[]},
]
},
{
id:6,
city:'曲靖市',
child:[
{id:7,city:'麒麟区',child:[
{id:16,city:'开发区',child:[]},
{id:17,city:'麒麟花园',child:[]},
]},
{id:8,city:'马龙县',child:[]},
]
},
]
},
{
id:9,
city:'贵州省',
child:[
{
id:10,
city:'贵阳市',
child:[
{id:11,city:'南明区',child:[]},
{id:12,city:'云岩区',child:[]},
]
},
{
id:13,
city:'六盘水',
child:[
{id:14,city:'钟山区',child:[]},
{id:15,city:'六枝特区',child:[]},
]
},
]
}
];
function createTree(data){
var content = '<ul>';
for(var i=0; i<data.length;i++){
content += '<li><span>+ </span><a data-id="' + data[i].id + '">'+ data[i].city + '</a>';
if(data[i].child.length>0){
content += createTree(data[i].child);
}
content += '</li>';
}
content += '</ul>';
return content;
}
$('#treedemo').html(createTree(data));
$('#treedemo').on('click',function(e){
var targetNode = $(e.target);
var nodeName = targetNode.get(0).tagName.toLowerCase();
if(nodeName == "span"){
$(e.target).parent().children("ul").toggle();
}
if(nodeName == "a"){
console.log($(e.target).data('id'));
}
});
</script>
</body>
</html>