需求
用JS实现树形结构,原本的数据是数组类型,需要先把数据进行处理,然后在页面上渲染DOM,注意点有以下几点:
1、data必须含有id和fatherId来表示他们的层级关系
2、js动态创建DOM的实现方式是先创建一个div,然后把生成的元素appendChild给这个div
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.treeItem > .treeItem{
padding-left: 10px;
cursor: pointer;
}
.itemIcon {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background: red;
margin-right: 10px;
}
</style>
<body>
<div id="d0" class="treeItem"></div>
<script>
// 数据
let data = [{
"id": "1",
"name": "1",
"fatherId": "0",
},
{
"id": "2",
"name": "1-1",
"fatherId": "1"
},
{
"id": "3",
"name": "1-2",
"fatherId": "1"
},
{
"id": "4",
"name": "1-1-1",
"fatherId": "2"
},
{
"id": "5",
"name": "1-1-2",
"fatherId": "2"
},
{
"id": "6",
"name": "2",
"fatherId": "0"
},
{
"id": "7",
"name": "1-2-1",
"fatherId": "3"
}
];
// 处理数据
//1、 先把数据处理成map
const map = {};
const val = [];
data.forEach((item) => {
map[item.id] = item;
});
// 2、遍历之后,形成树形结构
data.forEach((item) => {
const parent = map[item.fatherId];
if (parent) {
(parent.children || (parent.children = [])).push(item);
} else {
val.push(item);
}
});
console.log("映射",map)
console.log("数组",val)
// 动态生成html
// const tree = document.getElementById("tree");
function createLi(data) {
// 父元素id
const fid = `d${data.fatherId}`;
const div = document.getElementById(fid);
// 创建一个子元素div,添加给父元素
const treeItem = document.createElement("div");
treeItem.id = `d${data.id}`;
treeItem.className = "treeItem";
treeItem.innerHTML = data.name;
div.appendChild(treeItem);
// 如果是children,内部调用
if (data.children) {
data.children.forEach(d => {
createLi(d);
});
}
}
val.forEach(v => {
createLi(v);
})
</script>
</body>
</html>