jQuery zTree loads the tree menu function

  • 2021-01-06 00:26:57
  • OfStack

Because the project needs to design the tree menu function, so Baidu find relevant information, found a lot of zTree information, feel quite good, and zTree official also has API document, introduced very detailed, after 1 time of trouble, finally to get out, so to write down, is also a summary of learning zTree.

Introduction to zTree:

1, zTree is the use of JQuery core code, to achieve a set of Tree plug-in can complete most common functions

2. zTree v3.0 divides the core code according to its functions. Unneeded code can be loaded without load

3, the use of delayed loading technology, tens of thousands of nodes easily loaded, even in IE6 can basically do seckill

4, Compatible with IE, FireFox, Chrome, Opera, Safari and other browsers

5. Support JSON data

6, Support static and ES32en asynchronous loading node data

7, Support any change of skin/custom icon (depending on css)

8, Support extremely flexible checkbox or radio selection function

9. Provide multiple event response callbacks

10, flexible editing (add/delete/change/check) function, can drag and drop nodes at will, but also can drag and drop multiple nodes

11, Multiple instances of Tree can be generated in one page

Description of core functions and properties:

Core: zTree(setting, [zTreeNodes])

This function takes one data object setting in JSON format and one data object zTreeNodes in JSON format to create Tree.

Core parameters: setting

zTree parameter configuration is done here, in a nutshell: tree style, events, access path and so on are configured here


var setting = { 
 showLine: true, 
 checkable: true 
 };

Because there are too many parameters, please refer to zTreeAPI for details

Core parameters: zTreeNodes

The data set of all nodes of zTree is made up of the data structure of JSON objects. Simply put, all the information of the tree is saved in the format of Json

1, zTree's official website: http: / / www ztree. me/v3 / main php # _zTreeInfo

The zTree source code, examples and API can be downloaded from the official website. API by the author of pdf is very detailed

The acquisition of node data on zTree is divided into static (directly defined) and dynamic (backend database loading)

Specific configuration steps:

Step 1 -- Introduce the relevant files


<link rel="stylesheet" href="ztree/css/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="js/jQuery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="ztree/js/jquery.ztree.core-3.5.min.js"></script>
<script type="text/javascript" src="ztree/js/jquery.ztree.excheck-3.5.min.js"></script>

Remark:

1), The first (zTreeStyle.css) is the css file of zTree, which is introduced to present the tree-like structure style.

jquery-1.9.1.min.js) jQuery (jquery-1.9.1.min.js) jQuery (jquery-1.9.1.min.js)

3), the third (jquery.ztree.core-3.5.min.js) is the core js file, this is required.

4), the last one (js/jquery. ztree. excheck - 3.5 min. js) is expanding files, it is mainly used for the function of the radio buttons and check boxes, because use the checkbox, so also want to introduce.

Step 2 -- Relevant configuration (for detailed configuration, please refer to API documentation on the official website)


var zTree;
var setting = {
 view: {
 dblClickExpand: false,// Whether the parent node's identity is automatically expanded when a node is double-clicked 
 showLine: true,// Whether to display wires between nodes 
 fontCss:{'color':'black','font-weight':'bold'},// Font style function 
 selectedMulti: false // Sets whether multiple nodes are allowed to be selected at the same time 
 },
 check:{
 //chkboxType: { "Y": "ps", "N": "ps" },
 chkStyle: "checkbox",// Check box type 
 enable: true // Whether to display on each node  CheckBox 
 },
 data: {
 simpleData: {// Simple data schema 
  enable:true,
  idKey: "id",
  pIdKey: "pId",
  rootPId: ""
 }
 },
 callback: {
 beforeClick: function(treeId, treeNode) {
  zTree = $.fn.zTree.getZTreeObj("user_tree");
  if (treeNode.isParent) {
  zTree.expandNode(treeNode);// If it is a parent node, expand the node 
  }else{
  zTree.checkNode(treeNode, !treeNode.checked, true, true);// Click to check, and click again to uncheck 
  }
 }
 }
};

Step 3 -- Load node data and present a tree structure

1), html page, simply put one ul, the data will be automatically loaded into the ul element


<body>
 <div class="zTreeDemoBackground left">
 <ul id="user_tree" class="ztree" style="border: 1px solid #617775;overflow-y: scroll;height: 500px;"></ul>
 </div>
</body>

2) Load data in js

1. Static mode (defined directly)


var zNodes =[
 { id:1, pId:0, name:"test 1", open:false},
 { id:11, pId:1, name:"test 1-1", open:true},
 { id:111, pId:11, name:"test 1-1-1"},
 { id:112, pId:11, name:"test 1-1-2"},
 { id:12, pId:1, name:"test 1-2", open:true},
   ];
   
$(document).ready(function(){
 $.fn.zTree.init($("#user_tree"), setting, zNodes);
});
function onCheck(e,treeId,treeNode){
 var treeObj=$.fn.zTree.getZTreeObj("user_tree"),
 nodes=treeObj.getCheckedNodes(true),
 v="";
 for(var i=0;i<nodes.length;i++){
 v+=nodes[i].name + ",";
 alert(nodes[i].id); // Gets the value of the selected node 
 }
}

2. Dynamic mode (load from background database)


/**
 *  Page initialization 
 */
$(document).ready(function(){
 onLoadZTree();
});

/**
 *  Load the tree structure data 
 */
function onLoadZTree(){
 var treeNodes;
 $.ajax({
 async:false,// Whether the asynchronous 
 cache:false,// Whether to use caching or not 
 type:'POST',// Request method: post
 dataType:'json',// Data transmission format: json
 url:$('#ctx').val()+"SendNoticeMsgServlet?action=loadUserTree",// The request of action The path 
 error:function(){
  // Request failure handler function 
  alert(' Dear, request failed! ');
 },
 success:function(data){
// console.log(data);
  // The post-handler function for successful request 
  treeNodes = data;// Encapsulating the backend is simple Json The format is assigned to treeNodes
 }
 });
 
 var t = $("#user_tree");
 t = $.fn.zTree.init(t, setting, treeNodes);
}

java background loading data code:

1. Define the VO class for tree. This is not necessary because I need to use other operations


/**
 * zTree Tree-structured objects VO class 
 * 
 * @author Administrator
 * 
 */
public class TreeVO {
 private String id;// node id
 private String pId;// The parent node pId I Must be capitalized 
 private String name;// The name of the node 
 private String open = "false";// Whether or not to expand the tree node, default does not expand 

 public String getId() {
 return id;
 }

 public void setId(String id) {
 this.id = id;
 }

 public String getpId() {
 return pId;
 }

 public void setpId(String pId) {
 this.pId = pId;
 }

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getOpen() {
 return open;
 }

 public void setOpen(String open) {
 this.open = open;
 }

}

2, query the database, and the structure of sql field also if id pId, name, open (optional) this format (note: the middle pId I must be capitalized), and then results in TreeVO class.


/**
 *  Load the tree structure data 
 * @param request
 * @param response
 * @throws IOException 
 */
 public void loadUserTree(HttpServletRequest request, HttpServletResponse response) throws IOException{
 WeiXinUserService weixinUserService = new WeiXinUserServiceImpl();
 List<TreeVO> user_tree_list = weixinUserService.getUserTreeList();
 String treeNodesJson = JSONArray.fromObject(user_tree_list).toString();// will list List conversion to json format   return 
 
 PrintWriter out = response.getWriter();
 // using Json The plugin will Array Converted to Json format  
 out.print(treeNodesJson);
 
 // Release resources 
 out.close();
 }

For more information about the jQuery control, please refer to the jQuery plugin.

Here to complete the whole operation, �, writing is not good, not the language naturally, you forgive me! Learn together and grow together!


Related articles: