使用无序列表ul实现多级菜单

2022-07-31,,

首先要求后端传来的菜单数据必须包含:

id---菜单id
pid---父菜单id

整体思想:首先渲染出整个菜单(不包含父子关系),再用js将各标签分组、挂载到父结点上。

这里给各个菜单增加自定义属性pid,如下(jsp代码):

<ul class="navbar" style="width: 100%">
        <c:forEach var="menu" items="${menus}">
            <li id="${menu.menuId}" data-pid="${menu.pId}">
                <a href="${menu.url}" target="center" onclick="showMenu(this);return false;">${menu.menuName}
                    <img src="./img/open.png" alt="">
                </a>
            </li>
        </c:forEach>
    </ul>

其中,data-pid(data-xxx-xxx格式)为目前使用较多的自定义属性定义方式

在js中的代码为:

//html加载完毕后执行
window.onload = function () {
            var list = document.getElementsByTagName("li");
            for (var i = 0; i < list.length; i++) {
                if (list[i].dataset.pid === "") {
                    //这里是顶级菜单
                } else if (list[i].dataset.pid !== "") {
                    //这里是子结点
                    //取出pid
                    var pid = list[i].dataset.pid;
                    var pele = document.getElementById(pid);
                    //寻找父菜单
                    if (document.getElementById("u" + pid) == null) {
                        //不存在则创建
                        var ul = document.createElement("ul");
                        ul.setAttribute("id", "u" + pid);
                        ul.appendChild(list[i]);
                        pele.appendChild(ul);
                    } else {
                        //存在则添加
                        var ul = document.getElementById("u" + pid);
                        ul.appendChild(list[i]);
                    }
                }
            }
        }

 

本文地址:https://blog.csdn.net/qq_41968029/article/details/107610917

《使用无序列表ul实现多级菜单.doc》

下载本文的Word格式文档,以方便收藏与打印。