ztree帶有選項框的樹形菜單使用

 1.ztree簡介

zTree 是一個依靠 jQuery 實現的多功能 「插件」。優異的性能、靈活的配置、多種功能的組合是 zTree 最大優勢。專門適合項目開發,尤爲是 樹狀菜單、樹狀數據的Web顯示、權限管理等等。
zTree 是開源免費的軟件(MIT 許可證)。在開源的做用下,zTree 愈來愈完善,目前已經擁有了很多粉絲,而且從此還會推出更多的 zTree 擴展功能庫,讓 zTree 更增強大。

2.ztree入門

    步驟 一、文件準備javascript

    將須要使用的 zTree v3.x 相關的 js、css、img 文件分別放置到相應目錄,而且保證相對路徑正確css

  步驟 二、編寫 html 頁面html

    按照如下代碼,製做 html 頁面,訪問試試看吧,注意:
      1) "<!DOCTYPE html>" 是必需的!
      2) zTree 的容器 className 別忘了設置爲 "ztree"
java

 1 <!DOCTYPE html>
 2 <HTML>
 3  <HEAD>
 4   <TITLE> ZTREE DEMO </TITLE>
 5   <meta http-equiv="content-type" content="text/html; charset=UTF-8">
 6   <link rel="stylesheet" href="demoStyle/demo.css" type="text/css">
 7   <link rel="stylesheet" href="zTreeStyle/zTreeStyle.css" type="text/css">
 8   <script type="text/javascript" src="jquery-1.4.2.js"></script>
 9   <script type="text/javascript" src="jquery.ztree.core-3.x.js"></script>
10   <SCRIPT LANGUAGE="JavaScript">
11    var zTreeObj; 12    // zTree 的參數配置,深刻使用請參考 API 文檔(setting 配置詳解)
13    var setting = {}; 14    // zTree 的數據屬性,深刻使用請參考 API 文檔(zTreeNode 節點數據詳解)
15    var zNodes = [ 16  {name:"test1", open:true, children:[ 17  {name:"test1_1"}, {name:"test1_2"}]}, 18  {name:"test2", open:true, children:[ 19  {name:"test2_1"}, {name:"test2_2"}]} 20  ]; 21  $(document).ready(function(){ 22  zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes); 23  }); 24   </SCRIPT>
25  </HEAD>
26 <BODY>
27 <div>
28    <ul id="treeDemo" class="ztree"></ul>
29 </div>
30 </BODY>
31 </HTML>
View Code

 

3.製做以下圖所示的案例

 

  步驟1.下載ztree插件node

        下載地址:  https://pan.baidu.com/s/11rAiA5Gsr7kIoFIqA5KSCAjquery

 步驟2.將插件引入到項目中ajax

<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代碼spring

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

 步驟4.初始話樹chrome

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加載數據,必定要保證在 初始化樹以前 加載數據,若是先加載數據在初始化樹會出問題json

附加 完整生產代碼

1.html

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2  pageEncoding="UTF-8" %>
 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 4 <%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
 5 <%
 6     String path = request.getContextPath();  7     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/";  8 %>
 9 <!DOCTYPE html>
 10 <html lang="en">
 11 <head>
 12     <base href="<%=basePath%>">
 13     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
 14     <meta charset="UTF-8">
 15     <title>角色編輯</title>
 16     <link rel="stylesheet" href="static/layui/css/layui.css">
 17     <link rel="stylesheet" href="static/css/common.css">
 18     <link rel="stylesheet" href="static/css/schoolInfo.css">
 19     <link rel="stylesheet" href="static/css/teacherInfo.css">
 20     <!--[if IE 8]>  21  <!-- <link rel="stylesheet" type="text/css" href="static/css/ie.css"/>-->
 22     <link rel="stylesheet" type="text/css" href="static/zTree/css/zTreeStyle/zTreeStyle.css"/>
 23     <script type="text/javascript" src="static/zTree/js/jquery-1.4.4.min.js"></script>
 24     <script type="text/javascript" src="static/zTree/js/jquery.ztree.core.js"></script>
 25     <script type="text/javascript" src="static/zTree/js/jquery.ztree.all.min.js"></script>
 26 
 27 
 28     <![endif]-->
 29     <style>
 30  .fz13 {
 31  font-size: 13px;
 32         }
 33 
 34  .xy-layer-main {
 35  width: 73%;
 36  height: 60%;
 37         }
 38     </style>
 39 </head>
 40 <body class="content">
 41 <div id="app">
 42     <div class="xy-backdrop" hidden onclick="showFlashDialog()"><img src="static/images/loding.gif"></div>
 43     <p class="p-title"></p>
 44     <%--  <form class="layui-form row-between form" action="" enctype="multipart/form-data" id="teacher_role_form">--%>
 45 
 46     <div class="form-right fl layui-form">
 47         <p class="text-title">角色信息</p>
 48         <div class="flex-start b-bottom mt30">
 49             <div class="layui-form-item ">
 50                 <div class="layui-inline">
 51                     <label class="layui-form-label"><span class="fcred">*</span>角色名稱:</label>
 52                     <div class="layui-input-block wh20">
 53                         <input id="roleName" type="text" name="roleName" maxlength="10" lay-verify="name"
 54  onkeydown="if(event.keyCode==32) return false" autocomplete="off" placeholder="角色名稱"
 55  class="layui-input" value="${role.roleName}">
 56                     </div>
 57                 </div>
 58 
 59                 <div class="layui-inline">
 60                     <label class="layui-form-label"><span class="fcred">*</span>角色備註:</label>
 61                     <div class="layui-input-block wh20">
 62                         <input id="remark" type="text" name="remark" maxlength="10" lay-verify="name"
 63  onkeydown="if(event.keyCode==32) return false" autocomplete="off" placeholder="角色備註"
 64  class="layui-input" value="${role.remark}">
 65                     </div>
 66                 </div>
 67 
 68             </div>
 69         </div>
 70 
 71 
 72         <div class="b-bottom">
 73             <p class="text-title">角色菜單</p>
 74             <div class="layui-form-item mt30">
 75                 <div class="layui-inline" style="height: 400px">
 76                     <ul id="treeDemo" class="ztree" style="margin-top: 10px; width: 200px; height: 150px;">
 77                     </ul>
 78                </div>
 79             </div>
 80         </div>
 81 
 82 
 83         <!--修改信息-->
 84         <input id="roleId" value="${role.id}" hidden>
 85         <div class="layui-form-item text-center">
 86             <button id="myButton" type="submit"
 87  class="layui-btn layui-btn-radius bg-org box-shaow-org wh135px" lay-submit=""
 88  lay-filter="demoRole">保存  89             </button>
 90         </div>
 91     </div>
 92     <%--  </form>--%>
 93 
 94 
 95 </div>
 96 <script src="static/layui/layui.js"></script>
 97 <script src="static/js/jquery-1.8.3.js"></script>
 98 <script src="static/js/public.js"></script>
 99 <script src="static/js/jquery.form.js"></script>
100 <script type="text/javascript" src="static/zTree/js/jquery-1.4.4.min.js"></script>
101 <script type="text/javascript" src="static/zTree/js/jquery.ztree.core.js"></script>
102 <script type="text/javascript" src="static/zTree/js/jquery.ztree.all.min.js"></script>
103 <%--<script type="text/javascript" src="static/zTree/js/jquery.ztree.excheck.js"></script>--%>
104 
105 
106 <script type="text/javascript">
107     var aa = {aa: 1}; 108     var isIE = /msie/i.test(navigator.userAgent) && !window.opera; 109     var imgAA = 0; 110 
111     var teacherImg, layer, form; 112  layui.use(['form'], function () { 113  form = layui.form; 114  layer = layui.layer; 115 
116         //監聽提交
117  form.on('submit(demoRole)', function (data) { 118 
119 
120  }); 121  }); 122     /** 123  * 保存選中的數據 124      */
125  $("#myButton").click(function () { 126         var treeObj = $.fn.zTree.getZTreeObj("treeDemo"); 127         var nodes = treeObj.getCheckedNodes(true); 128         if (0 === nodes.length) { 129  alert("請選擇!"); 130             return; 131  } 132         var dataNodes = ""; 133         for (var i = 0; i < nodes.length; i++) { 134  dataNodes += nodes[i].id + ","; 135  } 136  updateOrAddRole(dataNodes); 137 
138  }); 139     function updateOrAddRole(menuIds) { 140         var roleId = $("#roleId").val(); 141         var roleName = $("#roleName").val(); 142         var remark = $("#remark").val(); 143         var params = { 144  roleId: roleId, 145  menuIds: menuIds, 146  roleName: roleName, 147  remark: remark 148  }; 149         var url = "permission/updateOrAddRole"; 150  uwillBeAsyncTrue.getdata(url, params, function (data) { 151             var code = data.code; 152             if (code == '0000') { 153  layer.msg("操做成功"); 154  setTimeout(function test() { 155                     var index = parent.layer.getFrameIndex(window.name); //獲取窗口索引
156  $('#search', window.parent.document).click(); 157  parent.layer.close(index); // 關閉layer
158  }, 800); 159  } else { 160  layer.alert("操做失敗", {icon: 2}); 161  } 162  }); 163  } 164     function createTree(url,params, treeId) { 165         var zTree; //用於保存建立的樹節點
166         var setting = { //設置
167  check: { 168  enable: true, 169  chkboxType: { 170                     "Y": "ps", 171                     "N": "ps"
172  } 173  }, 174  view: { 175  showLine: true, //顯示輔助線
176  dblClickExpand: true
177  }, 178  data: { 179  simpleData: { 180  enable: true, 181  idKey: "id", 182  pIdKey: "pid", 183  rootPId: 0
184  } 185  } 186  }; 187  $.ajax({ //請求數據,建立樹
188  type: 'GET', 189  url: url, 190  data: params, 191  dataType: "json", //返回的結果爲json
192  success: function (data) { 193  zTree = $.fn.zTree.init($(treeId), setting, data); //建立樹
194  }, 195  error: function (data) { 196  alert("建立樹失敗!"); 197  } 198  }); 199  } 200     function initTree() { 201         var roleId=$("#roleId").val(); 202         var params={ 203  roleId:roleId 204  }; 205  createTree("permission/menuData", params,"#treeDemo");//建立
206  } 207  initTree(); 208 </script>
209 </body>
210 </html>
View Code

2.數據格式拼接(請注意數據格式)

 1  @Override  2     public List<Map<String, Object>> menuData(Integer roleId) {  3         //封裝全部數據
 4         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  5         //獲取到 當前角色下的 菜單id
 6         List<PageData> list1;  7         if (roleId == null || roleId == -1) {  8             list1 = new ArrayList<>();  9         } else { 10             list1 = permissionDao.queryMenuBuyRoleId(roleId); 11  } 12         //查詢二級 和一下的菜單封裝
13         List<Menu> listTwo = teacherDao.queryMenu(2); 14         for (Menu tree_menu_two : listTwo) { 15             Map<String, Object> map = new HashMap<String, Object>(); 16             Integer id = tree_menu_two.getId(); 17             for (PageData roleMenu : list1) { 18                 Integer menuId = roleMenu.getInt("menuId"); 19                 if (id.equals(menuId)) { 20                     tree_menu_two.setChecked(true); 21                     break; 22  } 23  } 24             map.put("id", Integer.valueOf(tree_menu_two.getMenuLevel() + "" + id)); 25             map.put("mid", id); 26             map.put("name", tree_menu_two.getMenuName()); 27             map.put("menuUrl", tree_menu_two.getMenuUrl()); 28             map.put("menuOrder", tree_menu_two.getMenuOrder()); 29             map.put("menuIcon", tree_menu_two.getMenuIcon()); 30             map.put("checked", tree_menu_two.isChecked()); 31             Integer menuLevel = tree_menu_two.getMenuLevel(); 32             if (menuLevel > 1) { 33                 map.put("pid", Integer.valueOf((menuLevel - 1) + "" + tree_menu_two.getPid())); 34             } else { 35                 map.put("pid", 0); 36  } 37             map.put("mpid", tree_menu_two.getPid()); 38  list.add(map); 39  } 40         return list; 41     }
View Code

 完美!

相關文章
相關標籤/搜索