mysql创建一个二级菜单有id,parent_id,name,并用js组成菜单
时间: 2023-06-10 11:05:30 浏览: 64
非常感谢您的问题。针对您的问题,您可以按照以下步骤来创建一个二级菜单:
1.首先,在 MySQL 中创建一个名为 menu 的表,该表应包含 id,parent_id 和 name 字段。id 字段将充当每个菜单项的唯一标识符,parent_id 字段将指向每个菜单项的上级,如果该菜单项是顶级则指向 null。name 字段将包含每个菜单项的名称。
2.在 MySQL 中运行以下查询,以创建包含示例菜单项的菜单:
INSERT INTO menu (id, parent_id, name) VALUES
(1, null, '菜单 1'),
(2, 1, '菜单 1.1'),
(3, 1, '菜单 1.2'),
(4, null, '菜单 2'),
(5, 4, '菜单 2.1'),
(6, 4, '菜单 2.2');
3.在 HTML 中创建一个具有 id 为 menu 的 div 元素。
4.编写 JavaScript 代码来检索菜单项,并将其组成菜单。
以下是一个示例菜单代码的 JavaScript:
```JavaScript
// 获取菜单数据
function getMenuItems() {
// 发送 GET 请求以检索菜单项
return fetch('/menu_items')
.then(function(response) {
return response.json();
});
}
// 将菜单项组成菜单
function buildMenu() {
getMenuItems().then(function(menuItems) {
// 根据父级 ID 组织菜单项
const organized = menuItems.reduce(function(result, item) {
const parentID = item.parent_id || '';
result[parentID] = result[parentID] || [];
result[parentID].push(item);
return result;
}, {});
// 从顶级开始创建菜单
const root = organized[''];
const createMenu = function(menuItems) {
if (!menuItems) {
return;
}
const list = document.createElement('ul');
for (let i = 0; i < menuItems.length; i++) {
const item = menuItems[i];
const li = document.createElement('li');
const a = document.createElement('a');
a.innerText = item.name;
li.appendChild(a);
// 递归创建子菜单
const subMenu = createMenu(organized[item.id]);
if (subMenu) {
li.appendChild(subMenu);
}
list.appendChild(li);
}
return list;
};
// 将菜单添加到 DOM 中
const menu = createMenu(root);
document.getElementById('menu').appendChild(menu);
});
}
// 当 DOM 加载完成时创建菜单
document.addEventListener('DOMContentLoaded', function() {
buildMenu();
});
```
希望这可以帮助回答您的问题。如果您对这些步骤有任何疑问,请随时追问。
相关推荐
![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_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)
![](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)