先给出菜单请求回来的json格式:
除去外面的code和msg外,data内容是一个[]数组;每个数组里面是一个对象;有4个参数,一个标题(title),一个图标(icon),一个请求地址(url),最后还可能有个子集(list)。
{
"code": 0,
"msg": "",
"data": [{
"title": "一级滑块组件",
"icon": "layui-icon-auz",
"url": "component/slider/index.html"
},{
"title": "二级",
"icon": "layui-icon-home",
"list": [{
"title": "评分",
"icon": "layui-icon-app",
"url": "component/rate/index.html"
}, {
"title": "轮播",
"icon": "layui-icon-console",
"url": "component/carousel/index.html"
}]
},{
"title": "三级",
"icon": "layui-icon-home",
"list": [{
"title": "三级3",
"icon": "layui-icon-home",
"url": "component/colorpicker/index.html",
"list":[{
"title":"流加载",
"icon": "layui-icon-tips",
"url":"component/flow/index.html"
},{
"title":"工具",
"icon": "layui-icon-print",
"url":"component/util/index.html"
}]
},{
"title": "代码修饰",
"icon": "layui-icon-note",
"url": "component/code/index.html"
},{
"title": "百度",
"icon": "layui-icon-note",
"url": "https://www.baidu.com"
},{
"title": "网易",
"icon": "layui-icon-note",
"url": "https://www.163.com"
}]
}]
}
index.html页面中,我保留了第一个菜单
在index.html后面的js脚本中
<script src="../res/layui/layui.js"></script>
<script>
layui.config({
base: '../res/' // 静态资源所在路径
}).use(['index'],function () {
let $ = layui.$;
let layer = layui.layer;
let element = layui.element;
$.ajax({
url: "/json/a.json",
type: "GET",
dataType: "json",
success: function (res) {
layer.alert(JSON.stringify(res));
console.log("res:" + JSON.stringify(res));
let lists = res.data;
//先添加所有的主材单
$.each(res.data, function(i, obj) {
console.log(obj);
let content='<li class="layui-nav-item" data-name='+obj.action+'>';
//判断是否存在下一级栏目,存在就不跳转,不存在就跳转
if (obj.list == undefined) {
content+='<a lay-href="' + obj.url+ '"><i class="layui-icon '+obj.icon+'"></i><cite>'+obj.title+'</cite></a>';
} else {
content+='<a href="javascript:;"><i class="layui-icon '+obj.icon+'"></i><cite>'+obj.title+'</cite></a>';
}
//这里是添加所有的子菜单
content+=loadchild(obj);
content+='</li>';
$(".layui-nav-tree").append(content);
});
element.init();
},
error: function (jqXHR) {
alert("请求菜单失败,发生错误:"+ jqXHR.status);
layer.alert(JSON.stringify("请求菜单失败"));
}
});
function loadchild(obj) {
if(obj==null){
return;
}
let content='';
if(obj.list!=null && obj.list.length>0){
content+='<dl class="layui-nav-child">';
}else{
content+='<dl>';
}
if(obj.list!=null && obj.list.length>0){
$.each(obj.list,function(i,note) {
content += '<dd>';
// content += '<a lay-href="' + note.url + '">' + note.title + '</a>';
if (note.list == undefined) {
content+='<a lay-href="' + note.url+ '"><i class="layui-icon '+note.icon+'"></i><cite>'+note.title+'</cite></a>';
} else {
content+='<a href="javascript:;"><i class="layui-icon '+note.icon+'"></i><cite>'+note.title+'</cite></a>';
}
if (note.list == null) {
return;
}
content += loadchild(note);
content += '</dd>';
});
content+='</dl>';
}
return content;
}
});
</script>
效果如下:
附带代码解释:
打开index.html
ajax请求菜单json,返回数据;
在ajax请求里面第一次对返回json菜单进行解析处理,你们内部有个loadchild()函数对对子菜单等进行处理,这里直接进行了递归;