一、最終效果圖(這裏僅爲實現算法,並加載至頁面,不作任何css界面優化)javascript
註釋:本示例包含三級目錄菜單,但實際上可支持N級(可以使用該代碼自行測試)css
二、數據源html
菜單信息通常來源於數據庫中數據表,且爲自鏈接表,其中包含主要字段(主鍵,菜單名稱,父級id);前端
本示例在前端頁面中使用對象數組模擬從數據庫獲取菜單信息;java
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 }, ];
註釋:id——菜單主鍵id;name——菜單名稱;pid——父級idjquery
三、程序設計算法
菜單信息通常來源數據庫
//菜單列表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; }
註釋:本示例菜單使用ul無序列表演示,menus變量爲最終生成的菜單html數組
四、運行app
GetData(0, menuArry) $("body").append(menus);
註釋:GetData(0, menuArry),0——頂級菜單主鍵
五、完整代碼
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="jquery-1.8.3.min.js"></script> </head> <body> <script type="text/javascript"> $(function () { 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 }, ]; GetData(0, menuArry) $("body").append(menus); }); //菜單列表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; } </script> </body> </html>