How to use Layui to develop a navigation menu based on a tree structure
The navigation menu is one of the common components in web development, and the navigation menu based on the tree structure Can provide better user experience and functional completeness. This article will introduce how to use the Layui framework to develop a navigation menu based on a tree structure and provide specific code examples.
1. Preparation
Before starting development, you need to confirm that the Layui framework has been installed and the relevant Layui resource files have been correctly introduced into the required HTML page.
2. Data preparation
First, you need to prepare a navigation menu data that conforms to the tree structure. Each navigation item and its sub-navigation items can be represented using JSON format.
For example, we have prepared the following navigation menu data:
var menuData = [ { "id": 1, "name": "菜单1", "children": [ { "id": 11, "name": "子菜单1.1" }, { "id": 12, "name": "子菜单1.2", "children": [ { "id": 121, "name": "子菜单1.2.1" }, { "id": 122, "name": "子菜单1.2.2" } ] } ] }, { "id": 2, "name": "菜单2", "children": [ { "id": 21, "name": "子菜单2.1" }, { "id": 22, "name": "子菜单2.2" } ] }, { "id": 3, "name": "菜单3" } ];
3. HTML structure
In the HTML page, we need to add a container to host the navigation menu. An unordered list (ul) can be used to represent a tree structure.
For example, we add the following HTML structure:
4. JavaScript code
Next, we use JavaScript code to render the navigation menu.
layui.use(['tree', 'form'], function(){ var tree = layui.tree; tree.render({ elem: '#navMenu', // 绑定容器 data: menuData, // 导航菜单数据 showCheckbox: false, // 是否显示复选框 id: 'navMenuTree', // 自定义ID,用于相关操作 isJump: true, // 是否允许点击节点时弹出新窗口跳转 click: function(obj){ // 点击回调函数 // do something console.log(obj.data); // 获取点击的节点数据 } }); });
For example, you can use CSS styles to beautify the navigation menu and add corresponding event processing:
The above is a simple method of using Layui to develop a navigation menu based on a tree structure. Example. Through the Tree component provided by Layui, we can easily implement a tree-structured navigation menu, and can perform style customization and event processing according to actual needs. Hope this article is helpful to you!
The above is the detailed content of How to use Layui to develop a tree-structured navigation menu. For more information, please follow other related articles on the PHP Chinese website!