<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
dl dd {
display: none;
}
</style>
</head>
<body>
<div class="output"></div>
<script>
/* 三、列表数据转换为树形结构 */
let data = [{
id: 0,
pid: -1,
title: "微云"
},
{
id: 1,
pid: 0,
title: "我的文档"
},
{
id: 2,
pid: 0,
title: "我的音乐"
},
{
id: 2999,
pid: 1,
title: "js程序设计"
},
{
id: 29000,
pid: 1,
title: "js权威指南"
},
{
id: 23333,
pid: 2,
title: "王杰"
},
{
id: 244444,
pid: 2,
title: "张国荣"
},
{
id: 3,
pid: 2,
title: "周杰伦"
},
{
id: 4000,
pid: 3,
title: "稻香"
},
{
id: 4,
pid: 3,
title: "发如雪"
},
{
id: 600,
pid: 3,
title: "夜曲"
}
]
let box = document.querySelector(".output")
//渲染列表书
function arrayToTree(data, parent) {
var str = ""
data.forEach(element => {
if (element.pid == parent) {
var flag = data.some(function (params) {
return params.pid == element.id
})
str += ` <dl pid=${element.pid}>
<dt>${element.title}</dt>
<dd>${flag?arrayToTree(data,element.id):""}</dd>
</dl> `
}
});
return str
}
box.innerHTML = arrayToTree(data, -1)
let allDt = document.querySelectorAll("dt")
allDt.forEach(item => {
item.onclick = (e) => {
e.stopPropagation()
let allDd = item.nextElementSibling
allDd.style.display == "block" ? allDd.style.display = "none" : allDd.style.display = "block"
}
})
</script>
</body>
</html>