js实现递归菜单无限层
/*动态加载菜单*/ function dynamicMenu(data){ if (userID != "admin"){ //1.清空所有菜单 $("#menuList").empty(); //2.添加用户配置菜单 递归生成 var rootArr = new Array(); $.each( data, function(index, content) { var id = content.id; var name = content.name; var operate = content.operate; var parentId = content.parentID; if (null == parentId || parentId == ""){ $("#menuList").append(‘<li><a id=‘ + id + ‘ href="‘ + operate + ‘"><i class="fa fa-lg fa-fw fa-folder-open"></i> <span class="menu-item-parent">‘ + name + ‘</span></a></li>‘); rootArr.push(content); } }); var treeData = changeDataToKV(data); var result = createMenuTree(data); for(var i=0;i<rootArr.length;i++){ buildMenu(treeData,result,rootArr[i].id,rootArr[i].parentID); } } } function createMenuTree(data){ //创建搜索键值对 var result = {}; for(var i=0;i<data.length;i++) { var id = data[i].id; var pId = data[i].parentID; if(pId){ if(!result[pId] && pId != null && pId != ""){ result[pId] = []; } result[pId].push(id); } } return result; } function changeDataToKV(data){ var deepMap = new Array(); for(var i=0;i<data.length;i++){ if(data[i].id){ deepMap[data[i].id] = data[i]; } } return deepMap; } function buildMenu(treeData,result,id,pId){ if(pId){ // 1.先把自己append到父节点中 var obj = treeData[id]; $("#menuList li a[id=" + pId + "]").next().append("<li><a id=" + id + " href=" + obj.operate + "><i class=‘fa fa-fw fa-folder-open‘></i>" + obj.name + "</a></li>"); } var childrenIds = result[id]; if(childrenIds){ $("a[id="+id+"]").after("<ul></ul>"); for(var i=0;i<childrenIds.length;i++){ buildMenu(treeData,result,childrenIds[i],id); } } } /*根据角色ID查询角色下的菜单*/ getMenuByRoleIdForIndex(roleId); function getMenuByRoleIdForIndex(roleId){ $.ajax({ type: "POST", dataType: "json", url: ‘getMenuByRoleId.do‘, data:{roleId:roleId}, beforeSend: function(XMLHttpRequest) { XMLHttpRequest.setRequestHeader("token",token); }, success: function (data) { var menuData = data.data; dynamicMenu(menuData); }, error: function(data) { ZD.showWarning("error:"+data.responseText); }, async:false }); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。