用js生成一个三级分类列表
时间: 2024-05-10 19:19:53 浏览: 18
好的,下面是生成三级分类列表的JS代码:
```
var data = [
{
label: '分类1',
children: [
{
label: '子分类1',
children: [
{
label: '子子分类1',
},
{
label: '子子分类2',
}
]
},
{
label: '子分类2',
children: [
{
label: '子子分类3',
},
{
label: '子子分类4',
}
]
}
]
},
{
label: '分类2',
children: [
{
label: '子分类3',
children: [
{
label: '子子分类5',
},
{
label: '子子分类6',
}
]
},
{
label: '子分类4',
children: [
{
label: '子子分类7',
},
{
label: '子子分类8',
}
]
}
]
}
];
function buildTree(data, parent) {
var ulEl = document.createElement('ul');
data.forEach(function(item) {
var liEl = document.createElement('li');
if (item.children && item.children.length) {
liEl.innerHTML = item.label;
buildTree(item.children, liEl);
} else {
liEl.innerHTML = '<a href="#">' + item.label + '</a>';
}
ulEl.appendChild(liEl);
});
parent.appendChild(ulEl);
}
var container = document.querySelector('#container');
buildTree(data, container);
```
你可以根据需要修改数据结构和生成的HTML标签。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)