要做到的效果图如下:
原始数据如下:
var data=[
{
name:"手机",
child:[
{name:"苹果",
child:[{name:"苹果14"},{name:"苹果13",
child:[{name:"苹果16系统",child:[{name:"目录"}]}]}]
}
]
},
{
name:"笔记本",
child:[
{name:"华硕",
child:[{name:"华硕vivobooks16"},{name:"华硕林耀双屏",}]
}
]
},
{
name:"服务器",
child:[
{name:"Linux"},{name:"wind",
child:[{name:"阿里"},{name:"腾讯",child:[
{name:"无限级",child:[
{name:"无限级2",child:[{name:"无限级3",child:[{
name:"无限级4"
}]}]}
]}
]}]
}
]
}
]
JS代码如下递归:
//递归无限目录树,自调用
function test(data){ //data获取数组所有的数据
var str = `<ul>`; //创建父级Ul
for(var i=0;i<data.length;i++){
str += `<li>${data[i].name}`; //遍历data中第i个name的值
if(data[i].child){ //遍历第i个data中是否包含child
str += test(data[i].child);
console.log(str);
};
str +=`</li>`;
}
str += `</ul>`;
return str;
};
document.querySelector(".cent").innerHTML = test(data);
html代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="cent">
</div>
</body>
<script src="index.js"></script>
</html>