js递归菜单
时间: 2023-07-23 21:16:31 浏览: 47
JS递归菜单是指通过递归函数来生成多层级的菜单列表。以下是一个简单的JS递归菜单的示例代码:
HTML代码:
```html
<div id="menu"></div>
```
JS代码:
```javascript
// 菜单数据
var menuData = [
{
name: '菜单1',
children: [
{
name: '子菜单1'
},
{
name: '子菜单2',
children: [
{
name: '子子菜单1'
},
{
name: '子子菜单2'
}
]
}
]
},
{
name: '菜单2',
children: [
{
name: '子菜单3'
}
]
}
];
// 生成菜单函数
function generateMenu(menuData, parentElement) {
// 创建ul元素
var ulElement = document.createElement('ul');
// 遍历菜单数据
menuData.forEach(function(menuItem) {
// 创建li元素
var liElement = document.createElement('li');
// 创建a元素
var aElement = document.createElement('a');
// 设置a元素的文本内容
aElement.textContent = menuItem.name;
// 将a元素添加到li元素中
liElement.appendChild(aElement);
// 判断是否有子菜单
if (menuItem.children && menuItem.children.length > 0) {
// 递归调用生成菜单函数,将子菜单添加到当前li元素中
generateMenu(menuItem.children, liElement);
}
// 将li元素添加到ul元素中
ulElement.appendChild(liElement);
});
// 将ul元素添加到父元素中
parentElement.appendChild(ulElement);
}
// 调用生成菜单函数,将菜单添加到页面中
var menuElement = document.getElementById('menu');
generateMenu(menuData, menuElement);
```
上面的代码会生成一个多层级的菜单列表,并添加到页面中。你可以根据实际需求修改菜单数据和样式。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)