运用 递归函数方法制作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
* {
padding: 0;
margin: 0;
}
.side-menu {
width: 300px;
border: 1px solid #ddd;
}
.side-menu ul li {
list-style: none;
}
.side-menu ul li a {
display: block;
text-decoration: none;
color: #222;
border-bottom: 1px solid #ddd;
}
.subnav {
display: none;
}
</style>
<body>
<div class="side-menu"></div>
</body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
$(function() {
$.ajax({
type: "GET",
url: "./1.JSON",
dataType: "json",
success: function(res) {
let dataArr = res;
let liStr = "";
let oUl = $("<ul></ul>");
let num = 5;
if (dataArr.length > 0) {
num += 5;
for (var i = 0; i < dataArr.length; i++) {
if (dataArr[i].childMenu != null && dataArr[i].childMenu.length > 0) { //有子菜单
liStr += "<li><a href=\"" + dataArr[i].href + "\"><i class=\"" + dataArr[
i].Left + "\"></i>" + dataArr[i].name + "<i class=\"" + dataArr[i]
.Right + "\"></i></a><ul class=\"subnav\">";
for (var j = 0; j < dataArr[i].childMenu.length; j++) {
liStr += getChildMenu(dataArr[i].childMenu[j], num);
}
liStr += "</ul></li>";
} else { //没有子菜单
liStr += "<li><a href=\"" + dataArr[i].href + "\"><i class=\"" + dataArr[
i].Left + "\"></i>" + dataArr[i].name + "<i class=\"" + dataArr[i]
.Right + "\"></i></a></li>";
}
}
oUl.html(liStr);
$(".side-menu").append(oUl);
}
}
})
function getChildMenu(dataArr, num) { //递归创建子菜单
let subStr = "";
num += 10;
if (dataArr.childMenu != null && dataArr.childMenu.length > 0) { //有子菜单
subStr += "<li><a style=\"padding-left:" + num + "px;\" href=\"" + dataArr.href +
"\"><i class=\"" + dataArr.Left + "\"></i>" + dataArr.name + "<i class=\"" + dataArr.Right +
"\"></i></a><ul class=\"subnav\">";
for (var j = 0; j < dataArr.childMenu.length; j++) {
subStr += getChildMenu(dataArr.childMenu[j], num);
}
subStr += "</ul></li>";
} else { //无子菜单
subStr += "<li><a style=\"padding-left:" + num + "px;\" href=\"" + dataArr.href +
"\"><i class=\"" + DataTransfer.Left + "\"></i>" + dataArr.name + "<i class=\"" + dataArr
.Right + "\"></i></a></li>";
}
return subStr;
}
(function SideMenuHandle() {
$('.side-menu').on("click", "li", function(event) {
event.stopPropagation();
// console.log($(this).find(".subnav").length)
if ($(this).find(".subnav").eq(0).is(":hidden")) {
$(this).find(".subnav").eq(0).show();
} else {
$(this).find(".subnav").eq(0).hide();
}
})
})();
})
</script>
</html>
制作做效果如下只是简易效果