Jquery+ztree loading a tree-shaped structure menu

Source: Internet
Author: User

Because the project needs to design a tree menu function, so Baidu to find relevant information, found ztree aspects of the material, feel very good, and Ztree official API documents, introduced very detailed, after a churn, finally to get out, so it is written down, It is also a summary of learning Ztree.


Introduction of Ztree:

1, Ztree is the use of JQuery's core code, to achieve a set of most common functions of the Tree plugin
2, Ztree v3.0 the core code according to the function of the division, the unwanted code can not load
3, the use of delayed loading technology, tens of thousands of nodes easily loaded, even under the IE6 can basically do the second kill
4, compatible with IE, FireFox, Chrome, Opera, Safari and other browsers
5. Support JSON Data
6. Support Static and Ajax loading node data asynchronously
7. Support any skin replacement/custom icon (depending on CSS)
8. Support for extremely flexible checkbox or radio selection function
9. Provide multiple event response callbacks
10, flexible editing (Add/delete/change/check) function, you can drag and drop the node, can also be multi-node drag yo
11. Multiple Tree instances can be generated at the same time within a page
12, simple parameter configuration to achieve flexible and changeable functions


The core functions and properties are described:


Core: Ztree (setting, [Ztreenodes])
This function takes a JSON-formatted data object setting and a JSON-formatted data object Ztreenodes to build the Tree.


Core parameter: Setting
Ztree parameter configuration is done here, simply say: Tree style, events, access path, etc. are configured here

setting Example:



Because there are too many parameters, see Ztreeapi for specific parameters.
Core parameter: Ztreenodes
Ztree is a collection of all node data, using a data structure composed of JSON objects, which simply says: This saves all of the tree's information in JSON format.

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


In the official website can download to the Ztree source code, the instance and the API, in which the author PDF API writes very detailed
The method of obtaining the node data of Ztree is divided into static (directly defined) and dynamic (background database loading).


Specific configuration steps:

The first step--the introduction of relevant documents

<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>

Note:
1, the first (ZTREESTYLE.CSS) is a ztree style CSS file, introduced this, in order to show the structure of the tree style,
2, the second (jquery-1.9.1.min.js) is a jquery file, because to use,
3, the third (jquery.ztree.core-3.5.min.js) is the core of Ztree JS file, this is necessary,
4, the last (js/jquery.ztree.excheck-3.5.min.js) is to expand the file, mainly for the function of single box and check box, because the use of the check box, so also want to introduce.


The second step-related configuration (detailed configuration, please refer to the website of the detailed API documentation)

var Ztree;var setting = {view: {dblclickexpand:false,//If the identity of the parent node is automatically expanded when the node is clicked showline:true,//whether to show connections between nodes fontcss:{' Color ': ' Black ', ' font-weight ': ' bold '},//font style function Selectedmulti:false//setting allows multiple nodes to be selected simultaneously},check:{//chkboxtype: {"Y": "PS "N": "PS"},chkstyle: "checkbox",//check box type enable:true//If checkbox},data is displayed on each node: {simpledata: {//Simple data mode 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 Tick, click Uncheck Again}}};

The third step--node data loading, showing the tree structure

1, HTML page, directly put a UL can, the data will eventually automatically loaded into this UL element inside

<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, JS in the loading of data

One, static mode (directly defined)

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}}

two, dynamic mode (load from the background database)
/** * Page Initialization */$ (document). Ready (function () {Onloadztree ();}); * * Load tree structure data */function onloadztree () {var treenodes;$.ajax ({async:false,//Whether asynchronous cache:false,//uses cache type: ' POST ',// Request method: Postdatatype: ' json ',//data transfer format: jsonurl:$ (' #ctx '). Val () + "Sendnoticemsgservlet?action=loadusertree",// Requested action path Error:function () {//Request failed Handler alert (' Pro, request failed! '),},success:function (data) {//console.log (data),///Request successful post-processing function TreeNodes = data;//Assign a simple JSON format wrapped in background to TreeNodes}}); var t = $ ("#user_tree"); t = $.fn.ztree.init (t, setting, treenodes);}

Java Background load Data code:

1, define the Vo class tree, this also can not be defined, because I want to use other operations, convenient some

/** * Ztree Tree Structure object VO class *  * @author Administrator *  */public class Treevo {private string id;//node Idprivate string pId ;//parent node PID I must capitalize the private string name;//node name private string open = "false";//whether to expand the tree node, the default does not expand the 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 is also Id,pid,name,open (optional) This format (note: The middle of the pId I must capitalize), and then encapsulate the results into the Treevo class.

/** * Load 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 ()//Convert list List to JSON format return printwriter out = Response.getwriter ();//Use JSON plugin to convert array to JSON format  out.print (Treenodesjson);//Release Resource Out.close ();}


Here completes the entire operation, eh Sass, the writing is not good, the organization language nature is not how, everybody forgive! Learn together and grow together!

Jquery+ztree loading a tree-shaped structure menu

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.