hutm页面内容
<h1>树形菜单</h1> <div class="wh"> <div id="tree_list"> </div> </div>
js内容
<script> let content = '';//字符串 let treeList = document.getElementById("tree_list");//获取dom元素 let data = [ { "name":"菜单1", "child":[ { "name":"菜单1-1", "child":[], }, { "name":"菜单1-2", "child":[ { "name":"菜单1-2-1", "child":[], }, { "name":"菜单1-2-2", "child":[], } ], }, { "name":"菜单1-3", "child":[], } ], }, { "name":"菜单2", "child":[], }, { "name":"菜单3", "child":[ { "name":"菜单3-1", "child":[], } ], }, { "name":"菜单4", "child":[ { "name":"菜单4-1", "child":[], } ], }, { "name":"菜单5", "child":[ { "name":"菜单5-1", "child":[], } ], } ] // 你的数据 render(data); //使用数据渲染页面 function render(arr){ for(let item of arr){ if(item.child != undefined && item.child.length > 0){ content += ` <p onclick="cut(event)">${item.name}<img src="./img/icon-down.png" alt=""></p> <div style="display:none"> `; render(item.child); content += `</div>`; }else{ content +=`<p>${item.name}</p>`; } } treeList.innerHTML = content; } //显示隐藏事件 function cut(e){ e = e || window.event; let targets = e.target || e.srcElement; let targetsNext = targets.nextElementSibling; let targetImg = targets.children[0]; console.log(targetsNext) $(targetsNext).slideToggle(300); $(targetImg).toggleClass("rota"); } </script>