[Layui]layui使用tree实现树形下拉菜单

时间:2025-04-02 15:55:38
<script src="~/layui/"></script> <script type="text/javascript"> layui.config({ base: '~/layui/' //静态资源所在路径 }); layui.use(['layer', 'tree', 'form'], function () { var $ = layui.jquery, layer = layui.layer, form = layui.form, tree = layui.tree; //初始化权限 function init_auth() { console.log("权限菜单初始化"); var data = []; $.ajax({ url: "http://localhost:8089/api/SysMenu/GetSysMenuList", //后台数据请求地址 type: "get", async: false, success: function (resut) { data = resut; var formatdata = []; for (var i in data) { // pId为0时表示为根节点 if (data[i].pid == '-1') { var tempObject = {}; tempObject.title = data[i].name; tempObject.id = data[i].id; tempObject.children = getChildren(tempObject.id); formatdata.push(tempObject); } } function getChildren(id) { //递归体 即对每条data逐条递归找children var tempArray = []; for (var i in data) { if (data[i].pid == id) { var tempChild = {}; tempChild.title = data[i].name; tempChild.id = data[i].id; if (selectChildren(data[i].id)) { //若存在子节点,继续递归;否则为叶节点,停止递归 tempChild.children = getChildren(data[i].id); } tempArray.push(tempChild); } } return tempArray; } function selectChildren(id) { // 是否存在子节点 for (var i in data) { if (data[i].pid == id) { return true; } } return false; } //转成符合要求的格式 console.log(formatdata); //基本演示 tree.render({ elem: '#meuntree' , data: formatdata , id: 'authlist' , isJump: true //是否允许点击节点时弹出新窗口跳转 , click: function (obj) { var data = obj.data; //获取当前点击的节点数据 //('状态:' + + '<br>节点数据:' + (data)); var $select = $($(this)[0].elem).parents(".layui-form-select"); $select.removeClass("layui-form-selected").find(".layui-select-title span").html(obj.data.title).end().find("input:hidden[name='selectID']").val(obj.data.id); var selectId = $("input[name='selectID']").val(); layer.msg("选择了token operator">+ selectId + "的数据" + '<br>节点数据:' + obj.data.title, { icon: 1, time: 5000, offset: '15px' }); } }); } }); //return data; }; init_auth(); // 默认选中 var checkNode = { id: 4 ,title: '用户管理' } var $select = $(".layui-form-select"); $select.removeClass("layui-form-selected").find(".layui-select-title span").html(checkNode.title).end().find("input:hidden[name='selectID']").val(checkNode.id); form.render(); $(".treeSelect").on("click", ".layui-select-title", function (e) { $(".layui-form-select").not($(this).parents(".layui-form-select")).removeClass("layui-form-selected"); $(this).parents(".treeSelect").toggleClass("layui-form-selected"); layui.stope(e); }).on("click", "dl i", function (e) { layui.stope(e); }); $(document).on("click", function (e) { $(".layui-form-select").removeClass("layui-form-selected"); }); }); </script>