json结构:
var Menu = [{ tit:"一级菜单", submenu:[{ tit:"二级菜单", url:"", func:function(){ alert('what do you want to do?'); } },{ tit:"二级菜单", func:function(){ alert('do what?'); }, submenu:[{ tit:"三级菜单", url:"", submenu:[{ tit:"四级菜单", url:"" },{ tit:"四级菜单", url:"" }] },{ tit:"三级菜单", url:"" }] }] },{ tit:"一级菜单", submenu:[{ tit:"二级菜单", url:"" },{ tit:"二级菜单", submenu:[{ tit:"三级菜单", url:"" },{ tit:"三级菜单", url:"" }] }] }];
构建菜单处理函数
/* * @构建树形菜单 * @arrJson:json数据 * @container:菜单容器 */ function menuTree(jsonArr,container,treeId){ var oText,oUrl; var oUl = document.createElement('ul'); for(var i = 0 ;i < jsonArr.length; i++){ var oLi = document.createElement('li'); oUrl = jsonArr[i].url || "javascript:void(0)"; oText = jsonArr[i].tit; if(jsonArr[i].submenu){ oLi.innerHTML =''+oText+''; menuTree(jsonArr[i].submenu,oLi);//递归构建子菜单 }else{ oLi.innerHTML = ''+oText+''; } //自定义函数 if(typeof jsonArr[i].func =="function"){ oLi.getElementsByTagName('a')[0].func = jsonArr[i].func; oLi.getElementsByTagName('a')[0].οnclick=function(){ this.func(); } } oUl.appendChild(oLi); } //最外层容器事件委托 if(treeId){ document.getElementById(treeId).onclick = function(e){ var event = e || window.event; var target = event.target||event.srcElement; var next = target.nextSibling; if(target.nodeName.toLowerCase() == "a"){ if(next){ if(next.style.display=="" || next.style.display=="block"){ next.style.display="none"; }else{ next.style.display="block"; } } } } } container.appendChild(oUl); }
完整demo:
json树形菜单 构建json树形菜单
效果图:
完整实例: