Home >Web Front-end >JS Tutorial >Introduction to JavaScript recursive algorithms
This article mainly introduces the JavaScript recursive algorithm to generate a tree menu, which has a certain reference value. Interested friends can refer to it
The example of this article shares with you how to generate a tree menu with js The specific code is for your reference. The specific content is as follows
1. Final rendering (This is only to implement the algorithm and load it into the page without any css interface optimization)
Note: This example contains a three-level directory menu, but it can actually support N levels (you can use this code to test it yourself)
2. Data source
Menu information generally comes from data tables in the database and is a self-joining table, which contains main fields (primary key, menu name, parent id);
This example is on the front-end page Use an object array to simulate obtaining menu information from the database;
var menuArry = [ { id: 1, name: "办公管理", pid: 0 }, { id: 2, name: "请假申请", pid: 1 }, { id: 3, name: "出差申请", pid: 1 }, { id: 4, name: "请假记录", pid: 2 }, { id: 5, name: "系统设置", pid: 0 }, { id: 6, name: "权限管理", pid: 5 }, { id: 7, name: "用户角色", pid: 6 }, { id: 8, name: "菜单设置", pid: 6 }, ];
Note: id - menu primary key id; name - menu name; pid - parent id
3. Programming
General source of menu information
//菜单列表html var menus = ''; //根据菜单主键id生成菜单列表html //id:菜单主键id //arry:菜单数组信息 function GetData(id, arry) { var childArry = GetParentArry(id, arry); if (childArry.length > 0) { menus += '<ul>'; for (var i in childArry) { menus += '<li>' + childArry[i].name; GetData(childArry[i].id, arry); menus += '</li>'; } menus += '</ul>'; } } //根据菜单主键id获取下级菜单 //id:菜单主键id //arry:菜单数组信息 function GetParentArry(id, arry) { var newArry = new Array(); for (var i in arry) { if (arry[i].pid == id) newArry.push(arry[i]); } return newArry; }
Note: This example menu uses ul unordered list Demonstration, the menu variable is the final generated menu html
4, run
##
GetData(0, menuArry) $("body").append(menus);Comment: GetData(0, menuArry), 0——Top menu primary key
5, complete code
The above is the detailed content of Introduction to JavaScript recursive algorithms. For more information, please follow other related articles on the PHP Chinese website!