zTree is the core code of JQuery to implement a set of Tree plug-ins that can accomplish most of the common 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]
This function accepts a JSON-formatted data object setting and a JSON-formatted data object zTreeNodes to create a Tree.
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:
- var setting = {
- showLine: true,
- checkable: true
- };
Because there are too many parameters, see the zTree API for details.
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:
- var zTreeNodes = [
- {"id":1, "name":"test1", "nodes":[
- {"id":11, "name":"test11", "nodes":[
- {"id":111, "name":"test111"}
- ]},
- {"id":12, "name":"test12"}
- ]},
- ......
- ];
(2) Examples of zTreeNodes with simple Array format (isSimpleData) with father-son relationship:
- var treeNodes = [
- {"id":1, "pId":0, "name":"test1"},
- {"id":11, "pId":1, "name":"test11"},
- {"id":12, "pId":1, "name":"test12"},
- {"id":111, "pId":11, "name":"test111"},
- ......
- ];
[Example 1] (Java code)
Refer to zTree's js and css on the page:
- <!-- ZTree Tree plug-in -->
- <link rel="stylesheet" href="<%=root%>/Web/common/css/zTreeStyle/zTreeStyle.css" type="text/css">
- <!-- <link rel="stylesheet" href="<%=root%>/Web/common/css/zTreeStyle/zTreeIcons.css" type="text/css"> -->
- <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
- var setting = {
- isSimpleData : true, //Whether the data is in simple Array format, default false
- treeNodeKey : "id", //In isSimpleData format, the current node id attribute
- treeNodeParentKey : "pId", //In isSimpleData format, the parent node id attribute of the current node
- showLine : true, //Whether to show connections between nodes
- checkable : true //Whether CheckBox is displayed on each node
- };
- var treeNodes = [
- {"id":1, "pId":0, "name":"test1"},
- {"id":11, "pId":1, "name":"test11"},
- {"id":12, "pId":1, "name":"test12"},
- {"id":111, "pId":11, "name":"test111"},
- ];
(3) Spanning tree structure when entering the page:
- var zTree;
- $(function() {
- zTree = $("#tree").zTree(setting, treeNodes);
- });
(4) Final view effect:
[Example 2] (Obtaining Json data in simple format from the background)
Background code encapsulates Json data in simple format:
- public void doGetPrivilegeTree() throws IOException{
- String s1 = "{id:1, pId:0, name:\"test1\" , open:true}";
- String s2 = "{id:2, pId:1, name:\"test2\" , open:true}";
- String s3 = "{id:3, pId:1, name:\"test3\" , open:true}";
- String s4 = "{id:4, pId:2, name:\"test4\" , open:true}";
- List<String> lstTree = new ArrayList<String>();
- lstTree.add(s1);
- lstTree.add(s2);
- lstTree.add(s3);
- lstTree.add(s4);
- //Converting Array to Json format using Json plug-ins
- response.getWriter().print(JSONArray.fromObject(lstTree).toString());
- }
(2) Pages use Ajax to get zTreeNodes data to regenerate trees
- var setting = {
- isSimpleData : true, //Whether the data is in simple Array format, default false
- treeNodeKey : "id", //In isSimpleData format, the current node id attribute
- treeNodeParentKey : "pId", //In isSimpleData format, the parent node id attribute of the current node
- showLine : true, //Whether to show connections between nodes
- checkable : true //Whether CheckBox is displayed on each node
- };
- var zTree;
- var treeNodes;
- $(function(){
- $.ajax({
- async : false,
- cache:false,
- type: 'POST',
- dataType : "json",
- url: root+"/ospm/loginInfo/doGetPrivilegeTree.action",//The action path of the request
- error: function () {//Request Failure Handler
- alert('request was aborted');
- },
- success:function(data){ //Successful post-processing functions are requested.
- alert(data);
- treeNodes = data; //Assign treeNodes a simple Json format encapsulated in the background
- }
- });
- zTree = $("#tree").zTree(setting, treeNodes);
- });
(3) Final display effect
[Example 3] Dynamic data acquisition from background, tree node provides right-click menu function
Configuration setting:
- var url = "/ospm/loginInfo/doGetPrivilegeTree.action";
- //zTree Basic Settings
- var setting = {
- async : true, //Asynchronous access to child node data is required, default false
- 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.
- asyncParam : ["id"], //Submitted required parameters related to node data
- isSimpleData : true, //Whether the data is in simple Array format, default false
- treeNodeKey : "id", //In isSimpleData format, the current node id attribute
- treeNodeParentKey : "parentId", //In isSimpleData format, the parent node id attribute of the current node
- nameCol : "privName", //In isSimpleData format, the current node name
- 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)
- showLine : true, //Whether to show connections between nodes
- callback : { //callback
- rightClick : zTreeOnRightClick //Right click event
- }
- };
(2) Configure the right-click event of the mouse and display the code of the right-click menu.
- //Display right-click menu
- function showRMenu(type, x, y) {
- $("#rMenu ul").show();
- if (type=="root") {
- $("#m_del").hide();
- $("#m_check").hide();
- $("#m_unCheck").hide();
- }
- $("#rMenu").css({"top":y+"px", "left":x+"px", "display":"block"});
- }
- //Hide the right-click menu
- function hideRMenu() {
- $("#rMenu").hide();
- }
- //Right-click event of mouse-create right-click menu
- function zTreeOnRightClick(event, treeId, treeNode) {
- if (!treeNode) {
- zTree.cancelSelectedNode();
- showRMenu("root", event.clientX, event.clientY);
- } else if (treeNode && !treeNode.noR) { //The noR attribute is true to denote the forbidden right-click menu
- if (treeNode.newrole && event.target.tagName != "a" && $(event.target).parents("a").length == 0) {
- zTree.cancelSelectedNode();
- showRMenu("root", event.clientX, event.clientY);
- } else {
- zTree.selectNode(treeNode);
- showRMenu("node", event.clientX, event.clientY);
- }
- }
- }
- <p><span style="background-color: #fafafa;"><!-- Right click menu div -->
- <div id="rMenu" style="position:absolute; display:none;">
- <li>
- <ul id="m_add" onclick="addPrivilege();"><li>increase</li></ul>
- <ul id="m_del" onclick="delPrivilege();"><li>delete</li></ul>
- <ul id="m_del" onclick="editPrivilege();"><li>edit</li></ul>
- <ul id="m_del" onclick="queryPrivilege();"><li>See</li></ul>
- </li>
- </div></span></p>
(3) Page loading generates tree and monitors mouse click events to hide right-click menu in time
- function reloadTree() {
- hideRMenu();
- zTree = $("#tree").zTree(setting, treeNodes);
- }
- var zTree;
- var treeNodes = [];
- $(function() {
- reloadTree();
- $("body").bind(//Hide the right-click menu when the mouse click event is not on the node
- "mousedown",
- function(event) {
- if (!(event.target.id == "rMenu" || $(event.target)
- .parents("#rMenu").length > 0)) {
- $("#rMenu").hide();
- }
- });
- });
(4) Background code obtains tree node information according to id
--------------------------------------- Action layer - ----------------------------------------------------------------------------------------------------------
- public void doGetPrivilegeTree() throws IOException{
- String sId = request.getParameter("id");
- int treeId = 0;
- if(sId!=null&&!"".equals(sId)){
- treeId = Integer.parseInt(sId);
- }
- List<Privilege> lstPriv = privilegeService.findPrivilegeTreeById(treeId);
- response.setCharacterEncoding("UTF-8");
- response.getWriter().print(JSONArray.fromObject(lstPriv).toString());
- }
--------------------------------------- Service Layer----------------------------------------------------------------------------------------------------------
- /**
- * Query the data of its subordinate nodes according to the node id
- */
- @SuppressWarnings("unchecked")
- @Override
- public List<Privilege> findPrivilegeTreeById(int treeId) {
- StringBuffer sbTree= new StringBuffer();
- sbTree.append("SELECT NEW Privilege(p.id,p.privName,p.description,p.status,p.isLeaf,p.parentId) FROM Privilege p ");
- sbTree.append("WHERE p.parentId=:treeId ");
- sbTree.append("AND p.status!=:del ");
- Map<String,Object> mapTree = new HashMap<String, Object>();
- mapTree.put("treeId", treeId);
- mapTree.put("del", Privilege.PRIV_STATUS_DELETE);
- return (List<Privilege>) privilegeDao.findByHql(sbTree.toString(), mapTree);
- }
_Final view effect: