html代码
```
<div class='list'>
...
</div>
```
css代码
```
<style>
ul {
list-style-type: none;
}
ul li span {
color: red;
border: 1px solid #1890ff;
/*内减*/
width: 15px;
height: 15px;
display: inline-block;
text-align: center;
border-radius: 50%;
vertical-align: middle;
margin-right: 10px;
line-height: 15px;
cursor: default;
}
</style>
```
js
```
var data = [{
name: "IT互联网",
child: [
{ name: "编程语言", child: [{ name: "java" }, { name: "c#/.net" }, { name: "python" }, { name: "前端开发" }] },
{ name: "移动开发", child: [{ name: "android开发" }, { name: "IOS开发" }] },
{ name: "游戏开发", child: [{ name: "phaser游戏开发" }, { name: "web游戏开发", child: [{ name: "2D游戏" }, { name: "3D游戏" }] }] }
]
},
{
name: "设计创作",
child: [
{ name: "平面设计", child: [{ name: "电商美工" }, { name: "综合平面设计" }, { name: "摄影后期" }] },
{ name: "UI设计", child: [{ name: "交互设计" }, { name: "webUI设计" }, { name: "游戏UI设计" }] },
{ name: "游戏开发" }
]
},
{
name: "升学考研",
child: [
{ name: "考研" }, { name: "大学" }, { name: "高中" }, { name: "初中" }
]
},
{
name: "职企考证",
child: [
{ name: "公务员", child: [{ name: "教师考试" }, { name: "建筑工程" }] }
]
}
];
$(function() {
// var str = "";
// str += "<ul>";
// for (var i = 0; i < data.length; i++) {
// str += "<li>" + data[i].name + "<li>";//一级目录
// if (data[i].child) {
// str += "<ul>";
// for (var j = 0; j < data[i].child.length; j++) {
// str += "<li>" + data[i].child[j].name + "</li>"; //二级目录
// if( data[i].child[j].child){
// str += "<ul>";
// for(var z = 0; z < data[i].child[j].child.length; z++){
// str += "<li>" + data[i].child[j].child[z].name + "</li>"; //三级目录
// }
// str += "</ul>";
// }
// }
// str += "</ul>";
// }
// }
// str += "</ul>";
// $('.list').html(str);
// function cretaTree(data){
// var str = "";
// str += "<ul>";
// for (var i = 0; i < data.length; i++) {
// str += "<li>" + data[i].name + "<li>";//一级目录
// if(data[i].child){
// str += cretaTree(data[i].child);//二级目录
// }
// }
// str += "</ul>";
// return str;
// }
// $('.list').html(cretaTree(data));
function cretaTree(data) {
var str = "";
str += "<ul>";
for (var i = 0; i < data.length; i++) {
str += "<li><span>-</span>" + data[i].name; //一级目录
if (data[i].child) {
str += cretaTree(data[i].child); //二级目录
}
str += "</li>"
}
str += "</ul>";
return str;
}
$('.list').html(cretaTree(data));
$('.list ul li').click(function(e) {
e.stopPropagation();
if ($(this).find('ul').is(':visible')) { //判断有无子集 //冒泡
$(this).find('ul').hide();
$(this).find('span').text('+');
} else {
$(this).find('ul').show();
$(this).find('span').text('-');
}
})
})
```