1.下载ztree
这里附上链接: https://gitee.com/zTree/zTree_v3
2.解压到要用到的项目里
3.开始操作
- 引入必要的文件
- 写相关的HTML代码
- js操作
js操作主要分三步
1.配置对象
2.显示的数据(只截取了一部分)
3.DOM节点
有些数据并不符合ztree的数据格式 我们要将数据封装成ztree需要的数据格式才行,以下数据格式才是ztree需要的
显然以上数据并不符合。所以我们进行数据封装
运行结果
附上完整代码
<!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">
<link rel="stylesheet" type="text/css" href="./zTree_v3/css/zTreeStyle/zTreeStyle.css" />
<script type="text/javascript" src="./zTree_v3/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="./zTree_v3/js/jquery.ztree.core.js"></script>
<script src="./树.js"></script>
<title>Document</title>
</head>
<body>
<div class="content_wrap">
<div class="zTreeDemoBackground left">
<!-- #treeDemo放置ztree的地方 -->
<ul id="treeDemo" class="ztree"></ul>
</div>
</div>
</body>
</html>
js代码
// 1.配置对象
var setting = {};
// 2.显示的数据
var arr = [{
id: 1,
name: '根编目',
cate_path: null
}, {
id: 2,
name: 'Java课程',
cate_path: '1.2'
}, {
id: 3,
name: 'Spring课程',
cate_path: '1.2.3'
}, {
id: 6,
name: 'Servlet课程',
cate_path: '1.2.6'
}, {
id: 4,
name: 'SpringBoot课程',
cate_path: '1.2.3.4'
}, {
id: 5,
name: 'Web课程',
cate_path: '1.5'
}, {
id: 7,
name: 'React课程',
cate_path: '1.5.7'
}, {
id: 8,
name: 'redux课程',
cate_path: '1.5.7.8'
}, {
id: 9,
name: 'HTML5课程',
cate_path: '1.5.9'
}, {
id: 10,
name: 'H5API课程',
cate_path: '1.5.7.9.10'
}, {
id: 11,
name: 'Python',
cate_path: '1.11'
}, {
id: 12,
name: 'Django课程',
cate_path: '1.11.12'
}];
var res = myTree(arr);
console.log(res)
// 3.DOM节点
$(function () {
// 将DOM与配置对象与数据绑定,显示树
$.fn.zTree.init($("#treeDemo"), setting, res);
})
//数据封装
function myTree(arr) {
arr.forEach(function (item, index, arr) {
if (item.cate_path != null) {
item.parentId = item.cate_path.split('.');
item.parentId = Number(item.parentId.splice(item.parentId.length - 2, 1).join());
} else {
item.parentId = null
}
item.children = [];
return item.parentId;
});
arr.forEach(function (item, index, arr) {
arr.forEach(function (item1, index1, arr1) {
if (item.id == item1.parentId) {
item.children.push(item1) //将parentId=item.id加到children中
}
return item;
});
});
arr = arr[0].children;
return arr;
}