The use of demo in ztree

Keywords: Attribute JSON JQuery IE

zTree is the core code of JQuery to implement a set of Tree plug-ins that can accomplish most of the common functions.

  • Compatible with IE, FireFox, Chrome and other browsers
  • Multiple Tree instances can be generated in one page at the same time
  • Support JSON data
  • Supporting one-time static generation and Ajax asynchronous loading
  • Support multiple event responses and feedback
  • Tree-enabled node movement, editing, deletion
  • Support arbitrary replacement of skin/personalized icons (depending on css)
  • Supporting extremely flexible checkbox or radio selection functions
  • Simple parameter configuration to achieve flexible functions

     

    zTree blog address: http://ztreeapi.iteye.com/

    At present, the author of zTree has been registered in ItEye. If there is anything to learn, you can go to the author's blog to learn, and the version of zTree has been updated many times. The following content is estimated to be quite different from the latest version. I can't guarantee that the following tutorial will be available in the latest version. ZTree is really a very powerful tree component, I hope it can help you all!

     

     

    The source code, instance and API of zTree can be downloaded on the official website, and the author's API of pdf is written in great detail (oh in Chinese).

     

    [Introduction to Some Functions and Attributes]

  • Core: zTree (set, [zTreeNodes])

    This function accepts a JSON-formatted data object setting and a JSON-formatted data object zTreeNodes to create a Tree.

     

  • Core parameters: set

    The parameter configuration of zTree is completed here. Simply put: tree style, event, access path and so on are all configured here.

    setting for example:

    1. var setting = {   
    2.     showLine: true,   
    3.     checkable: true   
    4. };   

     

    Because there are too many parameters, see the zTree API for details.

     

  • Core parameter: zTreeNodes

    All node data sets of zTree adopt data structure composed of JSON objects. Simply put, all information of the tree is saved in Json format.

    The format of zTreeNodes can be divided into two types: using Json format to nest parent-child relationship and Array simple format

    (1) Examples of the standard zTreeNodes with paternity:

    1. var zTreeNodes = [   
    2.     {"id":1, "name":"test1""nodes":[   
    3.       {"id":11, "name":"test11""nodes":[   
    4.         {"id":111, "name":"test111"}   
    5.       ]},   
    6.       {"id":12, "name":"test12"}   
    7.     ]},   
    8.     ......   
    9. ];   

    (2) Examples of zTreeNodes with simple Array format (isSimpleData) with father-son relationship:

    1. var treeNodes = [                                                                         
    2.     {"id":1, "pId":0, "name":"test1"},   
    3.     {"id":11, "pId":1, "name":"test11"},   
    4.     {"id":12, "pId":1, "name":"test12"},   
    5.     {"id":111, "pId":11, "name":"test111"},   
    6.     ......   
    7. ];   

     

     

    [Example 1] (Java code)

    Refer to zTree's js and css on the page:

    1. <!-- ZTree Tree plug-in -->  
    2. <link rel="stylesheet" href="<%=root%>/Web/common/css/zTreeStyle/zTreeStyle.css" type="text/css">  
    3. <!-- <link rel="stylesheet" href="<%=root%>/Web/common/css/zTreeStyle/zTreeIcons.css" type="text/css">  -->  
    4. <script type="text/javascript" src="<%=root%>/Web/common/js/jquery-ztree-2.5.min.js"></script>  

    (2) Define setting s and zTreeNodes in script scripts

    1. var setting = {  
    2.         isSimpleData : true,              //Whether the data is in simple Array format, default false  
    3.         treeNodeKey : "id",               //In isSimpleData format, the current node id attribute  
    4.         treeNodeParentKey : "pId",        //In isSimpleData format, the parent node id attribute of the current node  
    5.         showLine : true,                  //Whether to show connections between nodes  
    6.         checkable : true                  //Whether CheckBox is displayed on each node  
    7.     };  
    8.   
    9. var treeNodes = [   
    10.     {"id":1"pId":0"name":"test1"},   
    11.     {"id":11"pId":1"name":"test11"},   
    12.     {"id":12"pId":1"name":"test12"},   
    13.     {"id":111"pId":11"name":"test111"},   
    14. ];   

    (3) Spanning tree structure when entering the page:

    1. var zTree;  
    1. $(function() {  
    2.     zTree = $("#tree").zTree(setting, treeNodes);  
    3.  });  

    (4) Final view effect:

    [Example 2] (Obtaining Json data in simple format from the background)

    Background code encapsulates Json data in simple format:

    1. public void doGetPrivilegeTree() throws IOException{  
    2.         String s1 = "{id:1, pId:0, name:\"test1\" , open:true}";  
    3.         String s2 = "{id:2, pId:1, name:\"test2\" , open:true}";  
    4.         String s3 = "{id:3, pId:1, name:\"test3\" , open:true}";  
    5.         String s4 = "{id:4, pId:2, name:\"test4\" , open:true}";  
    6.         List<String> lstTree = new ArrayList<String>();  
    7.         lstTree.add(s1);  
    8.         lstTree.add(s2);  
    9.         lstTree.add(s3);  
    10.         lstTree.add(s4);  
    11.         //Converting Array to Json format using Json plug-ins  
    12.         response.getWriter().print(JSONArray.fromObject(lstTree).toString());  
    13.     }  

     

    (2) Pages use Ajax to get zTreeNodes data to regenerate trees

    1. var setting = {  
    2.     isSimpleData : true,              //Whether the data is in simple Array format, default false  
    3.     treeNodeKey : "id",               //In isSimpleData format, the current node id attribute  
    4.     treeNodeParentKey : "pId",        //In isSimpleData format, the parent node id attribute of the current node  
    5.     showLine : true,                  //Whether to show connections between nodes  
    6.     checkable : true                  //Whether CheckBox is displayed on each node  
    7. };  
    8.   
    9. var zTree;  
    10. var treeNodes;  
    11.   
    12. $(function(){  
    13.     $.ajax({  
    14.         async : false,  
    15.         cache:false,  
    16.         type: 'POST',  
    17.         dataType : "json",  
    18.         url: root+"/ospm/loginInfo/doGetPrivilegeTree.action",//The action path of the request  
    19.         error: function () {//Request Failure Handler  
    20.             alert('request was aborted');  
    21.         },  
    22.         success:function(data){ //Successful post-processing functions are requested.     
    23.             alert(data);  
    24.             treeNodes = data;   //Assign treeNodes a simple Json format encapsulated in the background  
    25.         }  
    26.     });  
    27.   
    28.     zTree = $("#tree").zTree(setting, treeNodes);  
    29. });  

    (3) Final display effect

     

    [Example 3] Dynamic data acquisition from background, tree node provides right-click menu function

    Configuration setting:

    1. var url = "/ospm/loginInfo/doGetPrivilegeTree.action";  
    2.     //zTree Basic Settings  
    3.     var setting = {  
    4.         async : true//Asynchronous access to child node data is required, default false  
    5.         asyncUrl : root + url, //When async = true, the URL address of the asynchronous acquisition node is set to allow the reference of the function to be received.  
    6.         asyncParam : ["id"], //Submitted required parameters related to node data  
    7.         isSimpleData : true//Whether the data is in simple Array format, default false  
    8.         treeNodeKey : "id"//In isSimpleData format, the current node id attribute  
    9.         treeNodeParentKey : "parentId"//In isSimpleData format, the parent node id attribute of the current node  
    10.         nameCol : "privName",            //In isSimpleData format, the current node name  
    11.         expandSpeed : "fast"//Set the animation speed or cancel animation when the zTree node expands or collapses (three default definitions: "slow", "normal", "fast") or the millisecond value representing the animation duration (e.g. 1000)  
    12.         showLine : true//Whether to show connections between nodes  
    13.         callback : { //callback  
    14.             rightClick : zTreeOnRightClick   //Right click event  
    15.         }  
    16.     };  

     

    (2) Configure the right-click event of the mouse and display the code of the right-click menu.

    1. //Display right-click menu  
    2.     function showRMenu(type, x, y) {  
    3.         $("#rMenu ul").show();  
    4.         if (type=="root") {  
    5.             $("#m_del").hide();  
    6.             $("#m_check").hide();  
    7.             $("#m_unCheck").hide();  
    8.         }  
    9.         $("#rMenu").css({"top":y+"px""left":x+"px""display":"block"});  
    10.     }  
    11.     //Hide the right-click menu  
    12.     function hideRMenu() {  
    13.         $("#rMenu").hide();  
    14.     }  
    15.       
    16.     //Right-click event of mouse-create right-click menu  
    17.     function zTreeOnRightClick(event, treeId, treeNode) {  
    18.         if (!treeNode) {  
    19.             zTree.cancelSelectedNode();  
    20.             showRMenu("root", event.clientX, event.clientY);  
    21.         } else if (treeNode && !treeNode.noR) { //The noR attribute is true to denote the forbidden right-click menu  
    22.             if (treeNode.newrole && event.target.tagName != "a" && $(event.target).parents("a").length == 0) {  
    23.                 zTree.cancelSelectedNode();  
    24.                 showRMenu("root", event.clientX, event.clientY);  
    25.             } else {  
    26.                 zTree.selectNode(treeNode);  
    27.                 showRMenu("node", event.clientX, event.clientY);  
    28.             }  
    29.         }  
    30.     }  
    1. <p><span style="background-color: #fafafa;"><!-- Right click menu div -->  
    2.  <div id="rMenu" style="position:absolute; display:none;">  
    3.  <li>  
    4.  <ul id="m_add" onclick="addPrivilege();"><li>increase</li></ul>  
    5.  <ul id="m_del" onclick="delPrivilege();"><li>delete</li></ul>  
    6.  <ul id="m_del" onclick="editPrivilege();"><li>edit</li></ul>  
    7.  <ul id="m_del" onclick="queryPrivilege();"><li>See</li></ul>  
    8.  </li>  
    9.  </div></span></p>  

    (3) Page loading generates tree and monitors mouse click events to hide right-click menu in time

    1. function reloadTree() {  
    2.         hideRMenu();  
    3.         zTree = $("#tree").zTree(setting, treeNodes);  
    4.     }     
    5.       
    6.     var zTree;  
    7.     var treeNodes = [];  
    8.       
    9.   
    10. $(function() {  
    11.         reloadTree();  
    12.   
    13.         $("body").bind(//Hide the right-click menu when the mouse click event is not on the node  
    14.                 "mousedown",  
    15.                 function(event) {  
    16.                     if (!(event.target.id == "rMenu" || $(event.target)  
    17.                             .parents("#rMenu").length > 0)) {  
    18.                         $("#rMenu").hide();  
    19.                     }  
    20.                 });  
    21.     });  

     

    (4) Background code obtains tree node information according to id

    --------------------------------------- Action layer - ----------------------------------------------------------------------------------------------------------

    1. public void doGetPrivilegeTree() throws IOException{  
    2.         String sId = request.getParameter("id");  
    3.         int treeId = 0;  
    4.         if(sId!=null&&!"".equals(sId)){  
    5.             treeId = Integer.parseInt(sId);  
    6.         }  
    7.         List<Privilege> lstPriv = privilegeService.findPrivilegeTreeById(treeId);  
    8.         response.setCharacterEncoding("UTF-8");  
    9.         response.getWriter().print(JSONArray.fromObject(lstPriv).toString());  
    10.     }  

     

    --------------------------------------- Service Layer----------------------------------------------------------------------------------------------------------

    1. /** 
    2.      * Query the data of its subordinate nodes according to the node id 
    3.      */  
    4.     @SuppressWarnings("unchecked")  
    5.     @Override  
    6.     public List<Privilege> findPrivilegeTreeById(int treeId) {  
    7.         StringBuffer sbTree= new StringBuffer();  
    8.         sbTree.append("SELECT NEW Privilege(p.id,p.privName,p.description,p.status,p.isLeaf,p.parentId) FROM Privilege p ");  
    9.         sbTree.append("WHERE p.parentId=:treeId ");  
    10.         sbTree.append("AND p.status!=:del ");  
    11.           
    12.         Map<String,Object> mapTree = new HashMap<String, Object>();  
    13.         mapTree.put("treeId", treeId);  
    14.         mapTree.put("del", Privilege.PRIV_STATUS_DELETE);  
    15.           
    16.         return (List<Privilege>) privilegeDao.findByHql(sbTree.toString(), mapTree);  
    17.     }  

    _Final view effect:

  • Posted by vamosbenedikt on Fri, 22 Mar 2019 12:06:53 -0700