ztree带有选项框的树形菜单使用

时间:2023-11-28 21:16:50

1.ztree简介

zTree 是一个依靠 jQuery 实现的多功能 “插件”。优异的性能、灵活的配置、多种功能的组合是 zTree 最大优点。专门适合项目开发,尤其是 树状菜单、树状数据的Web显示、权限管理等等。
zTree 是开源免费的软件(MIT 许可证)。在开源的作用下,zTree 越来越完善,目前已经拥有了不少粉丝,并且今后还会推出更多的 zTree 扩展功能库,让 zTree 更加强大。

2.ztree入门

  步骤 1、文件准备

    将需要使用的 zTree v3.x 相关的 js、css、img 文件分别放置到相应目录,并且保证相对路径正确

  步骤 2、编写 html 页面

    按照以下代码,制作 html 页面,访问试试看吧,注意:
      1) "<!DOCTYPE html>" 是必需的!
      2) zTree 的容器 className 别忘了设置为 "ztree"

 <!DOCTYPE html>
<HTML>
<HEAD>
<TITLE> ZTREE DEMO </TITLE>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="demoStyle/demo.css" type="text/css">
<link rel="stylesheet" href="zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jquery.ztree.core-3.x.js"></script>
<SCRIPT LANGUAGE="JavaScript">
var zTreeObj;
// zTree 的参数配置,深入使用请参考 API 文档(setting 配置详解)
var setting = {};
// zTree 的数据属性,深入使用请参考 API 文档(zTreeNode 节点数据详解)
var zNodes = [
{name:"test1", open:true, children:[
{name:"test1_1"}, {name:"test1_2"}]},
{name:"test2", open:true, children:[
{name:"test2_1"}, {name:"test2_2"}]}
];
$(document).ready(function(){
zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
});
</SCRIPT>
</HEAD>
<BODY>
<div>
<ul id="treeDemo" class="ztree"></ul>
</div>
</BODY>
</HTML>

3.制作如下图所示的案例

 ztree带有选项框的树形菜单使用

步骤1.下载ztree插件

下载地址: https://pan.baidu.com/s/11rAiA5Gsr7kIoFIqA5KSCA

步骤2.将插件引入到项目中

 <link rel="stylesheet" type="text/css" href="static/zTree/css/zTreeStyle/zTreeStyle.css"/>
<script type="text/javascript" src="static/zTree/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="static/zTree/js/jquery.ztree.core.js"></script>
<script type="text/javascript" src="static/zTree/js/jquery.ztree.all.min.js"></script>

步骤3.html代码

 <ul id="treeDemo" class="ztree" style="margin-top: 10px; width: 200px; height: 150px;">
</ul>

步骤4.初始话树

 function createTree(url,params, treeId) {
var zTree; //用于保存创建的树节点
var setting = { //设置
check: {
enable: true,
chkboxType: {
"Y": "ps",
"N": "ps"
}
},
view: {
showLine: true, //显示辅助线
dblClickExpand: true
},
data: {
simpleData: {
enable: true,
idKey: "id",
pIdKey: "pid",
rootPId: 0
}
}
};
$.ajax({ //请求数据,创建树
type: 'GET',
url: url,
data: params,
dataType: "json", //返回的结果为json
success: function (data) {
zTree = $.fn.zTree.init($(treeId), setting, data); //创建树
},
error: function (data) {
alert("创建树失败!");
}
});
}
function initTree() {
var roleId=$("#roleId").val();
var params={
roleId:roleId
};
createTree("permission/menuData", params,"#treeDemo");//创建 permission/menuData 后台加载数据路由
}
initTree();

注意: 这里使用的是ajax加载数据,一定要保证在 初始化树之前 加载数据,如果先加载数据在初始化树会出问题

附加 完整生产代码

1.html

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/";
%>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="<%=basePath%>">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta charset="UTF-8">
<title>角色编辑</title>
<link rel="stylesheet" href="static/layui/css/layui.css">
<link rel="stylesheet" href="static/css/common.css">
<link rel="stylesheet" href="static/css/schoolInfo.css">
<link rel="stylesheet" href="static/css/teacherInfo.css">
<!--[if IE 8]>
<!-- <link rel="stylesheet" type="text/css" href="static/css/ie.css"/>-->
<link rel="stylesheet" type="text/css" href="static/zTree/css/zTreeStyle/zTreeStyle.css"/>
<script type="text/javascript" src="static/zTree/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="static/zTree/js/jquery.ztree.core.js"></script>
<script type="text/javascript" src="static/zTree/js/jquery.ztree.all.min.js"></script> <![endif]-->
<style>
.fz13 {
font-size: 13px;
} .xy-layer-main {
width: 73%;
height: 60%;
}
</style>
</head>
<body class="content">
<div id="app">
<div class="xy-backdrop" hidden onclick="showFlashDialog()"><img src="static/images/loding.gif"></div>
<p class="p-title"></p>
<%-- <form class="layui-form row-between form" action="" enctype="multipart/form-data" id="teacher_role_form">--%> <div class="form-right fl layui-form">
<p class="text-title">角色信息</p>
<div class="flex-start b-bottom mt30">
<div class="layui-form-item ">
<div class="layui-inline">
<label class="layui-form-label"><span class="fcred">*</span>角色名称:</label>
<div class="layui-input-block wh20">
<input id="roleName" type="text" name="roleName" maxlength="10" lay-verify="name"
onkeydown="if(event.keyCode==32) return false" autocomplete="off" placeholder="角色名称"
class="layui-input" value="${role.roleName}">
</div>
</div> <div class="layui-inline">
<label class="layui-form-label"><span class="fcred">*</span>角色备注:</label>
<div class="layui-input-block wh20">
<input id="remark" type="text" name="remark" maxlength="10" lay-verify="name"
onkeydown="if(event.keyCode==32) return false" autocomplete="off" placeholder="角色备注"
class="layui-input" value="${role.remark}">
</div>
</div> </div>
</div> <div class="b-bottom">
<p class="text-title">角色菜单</p>
<div class="layui-form-item mt30">
<div class="layui-inline" style="height: 400px">
<ul id="treeDemo" class="ztree" style="margin-top: 10px; width: 200px; height: 150px;">
</ul>
</div>
</div>
</div> <!--修改信息-->
<input id="roleId" value="${role.id}" hidden>
<div class="layui-form-item text-center">
<button id="myButton" type="submit"
class="layui-btn layui-btn-radius bg-org box-shaow-org wh135px" lay-submit=""
lay-filter="demoRole">保存
</button>
</div>
</div>
<%-- </form>--%> </div>
<script src="static/layui/layui.js"></script>
<script src="static/js/jquery-1.8.3.js"></script>
<script src="static/js/public.js"></script>
<script src="static/js/jquery.form.js"></script>
<script type="text/javascript" src="static/zTree/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="static/zTree/js/jquery.ztree.core.js"></script>
<script type="text/javascript" src="static/zTree/js/jquery.ztree.all.min.js"></script>
<%--<script type="text/javascript" src="static/zTree/js/jquery.ztree.excheck.js"></script>--%> <script type="text/javascript">
var aa = {aa: 1};
var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
var imgAA = 0; var teacherImg, layer, form;
layui.use(['form'], function () {
form = layui.form;
layer = layui.layer; //监听提交
form.on('submit(demoRole)', function (data) { });
});
/**
* 保存选中的数据
*/
$("#myButton").click(function () {
var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
var nodes = treeObj.getCheckedNodes(true);
if (0 === nodes.length) {
alert("请选择!");
return;
}
var dataNodes = "";
for (var i = 0; i < nodes.length; i++) {
dataNodes += nodes[i].id + ",";
}
updateOrAddRole(dataNodes); });
function updateOrAddRole(menuIds) {
var roleId = $("#roleId").val();
var roleName = $("#roleName").val();
var remark = $("#remark").val();
var params = {
roleId: roleId,
menuIds: menuIds,
roleName: roleName,
remark: remark
};
var url = "permission/updateOrAddRole";
uwillBeAsyncTrue.getdata(url, params, function (data) {
var code = data.code;
if (code == '0000') {
layer.msg("操作成功");
setTimeout(function test() {
var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
$('#search', window.parent.document).click();
parent.layer.close(index); // 关闭layer
}, 800);
} else {
layer.alert("操作失败", {icon: 2});
}
});
}
function createTree(url,params, treeId) {
var zTree; //用于保存创建的树节点
var setting = { //设置
check: {
enable: true,
chkboxType: {
"Y": "ps",
"N": "ps"
}
},
view: {
showLine: true, //显示辅助线
dblClickExpand: true
},
data: {
simpleData: {
enable: true,
idKey: "id",
pIdKey: "pid",
rootPId: 0
}
}
};
$.ajax({ //请求数据,创建树
type: 'GET',
url: url,
data: params,
dataType: "json", //返回的结果为json
success: function (data) {
zTree = $.fn.zTree.init($(treeId), setting, data); //创建树
},
error: function (data) {
alert("创建树失败!");
}
});
}
function initTree() {
var roleId=$("#roleId").val();
var params={
roleId:roleId
};
createTree("permission/menuData", params,"#treeDemo");//创建
}
initTree();
</script>
</body>
</html>

2.数据格式拼接(请注意数据格式)

  @Override
public List<Map<String, Object>> menuData(Integer roleId) {
//封装所有数据
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
//获取到 当前角色下的 菜单id
List<PageData> list1;
if (roleId == null || roleId == -1) {
list1 = new ArrayList<>();
} else {
list1 = permissionDao.queryMenuBuyRoleId(roleId);
}
//查询二级 和一下的菜单封装
List<Menu> listTwo = teacherDao.queryMenu(2);
for (Menu tree_menu_two : listTwo) {
Map<String, Object> map = new HashMap<String, Object>();
Integer id = tree_menu_two.getId();
for (PageData roleMenu : list1) {
Integer menuId = roleMenu.getInt("menuId");
if (id.equals(menuId)) {
tree_menu_two.setChecked(true);
break;
}
}
map.put("id", Integer.valueOf(tree_menu_two.getMenuLevel() + "" + id));
map.put("mid", id);
map.put("name", tree_menu_two.getMenuName());
map.put("menuUrl", tree_menu_two.getMenuUrl());
map.put("menuOrder", tree_menu_two.getMenuOrder());
map.put("menuIcon", tree_menu_two.getMenuIcon());
map.put("checked", tree_menu_two.isChecked());
Integer menuLevel = tree_menu_two.getMenuLevel();
if (menuLevel > 1) {
map.put("pid", Integer.valueOf((menuLevel - 1) + "" + tree_menu_two.getPid()));
} else {
map.put("pid", 0);
}
map.put("mpid", tree_menu_two.getPid());
list.add(map);
}
return list;
}

 完美!