jquery tree Control ztree Use summary _jquery

Source: Internet
Author: User
Tags visibility

0 Ztree Profile

The use of tree-shaped controls is essential in the application development process. Ztree is a multifunctional "tree plug-in" that relies on jQuery implementations. Excellent performance, flexible configuration, a combination of multiple functions is the biggest advantage of Ztree.

Characteristics of 0.0 Ztree
• The latest version of Ztree the core code in accordance with the function of the segmentation, unwanted code can not be loaded, such as ordinary use only need to load core jquery.ztree.core-3.5.js, need to use the Check function load jquery.ztree.excheck-3.5.min.js, need to use Edit function to load jquery.ztree.exedit-3.5.min.js
• The use of delayed loading technology, tens of thousands of nodes easy to load, even under the IE6 can basically do a second kill
• Compatible with IE, FireFox, Chrome, Opera, Safari and other browsers
• Support for JSON data
• Support for static and Ajax load node data asynchronously
• Support for any change of skin/Custom icon (depending on CSS)
• Support for extremely flexible checkbox or radio selection features
• Provides multiple event response callbacks
• Flexible editing (Add/delete/change/check) function, can drag and drop nodes, can also drag multiple nodes
• Multiple tree instances can be generated in one page at a time
• Simple parameter configuration implementation, flexible and changeable function

0.1 Ztree File Introduction
the Ztree downloaded from the Ztree website includes the following components

Metrostyle folder: Ztree's metro style related files (Pictures and CSS style sheets).
Ztreestyle folder: Ztree Standard style folder (picture and CSS style sheet)
js file: ZTree.all.js is a complete JS library, can simply load this file to achieve all Ztree functions, Ztree.core, Ztree.excheck, Ztree.exedit, Ztree.exhide is the segmentation of ztree according to function, corresponding basic function, check function, edit function, explicit hidden function respectively.

1 Basic use of Ztree

Creation of 1.0 Ztree
Add the JS and CSS references to ztree on the page, as Ztree based on jquery,jquery references are required.

<! DOCTYPE html> <HTML> <HEAD> <TITLE> ztree DEMO </TITLE> <meta http-equiv= "Content-type" Co Ntent= "text/html; Charset=utf-8 "> <link rel=" stylesheet "href=" Ztreestyle/ztreestyle.css "type=" Text/css "> <script type=" Text/javascript "src=" jquery-1.4.2.js "></script> <script type=" Text/javascript "src="
  Jquery.ztree.core-3.x.js "></script> <script language=" JavaScript "> var ztreeobj;  var setting = {}; Ztree parameter configuration, followed by the var znodes = [//Ztree data properties, where the standard JSON format is used {name: "Test1", open:true, children: [{NA Me: "Test1_1"}, {name: "Test1_2"}]}, {name: "Test2", open:true, children: [{name: ' Test2_1 '}, {name: "
  Test2_2 "}]}]; $ (document). Ready (function () {ztreeobj = $.fn.ztree.init ($ ("#treeDemo"), setting, znodes);//Initialize ztree, three parameters one at a time is a container (ZT
 REE container className do not forget to set to "Ztree"), parameter configuration, data source}); </SCRIPT> </HEAD> <BODY> <div> <ul id= "Treedemo" class= "Ztree" ></ul> </div> </BODY> </HTML> 

The results of the operation are as follows

Configuration of 1.1 Ztree
The configuration of the Ztree is in JSON format and is divided into view (visual interface related configuration), data (related configuration), check (check box related configuration), callback (callback function configuration for various events), Async (Ztree asynchronous load configuration), some of the configuration and instructions that we often use, and other detailed configuration can refer to the details of the Ztree official API documentation.

var setting = {view: {selectedmulti:true,//Set whether multiple nodes Showicon:true can be selected at the same time,//Set whether the node icon is displayed Showline:true ,//Set whether to display the link between node and node Showtitle:true,//Set whether to display the node's title prompt information}, data: {simpledata: {enable:false,/ /Set whether the simple data format is enabled (Ztree supports standard data formats with simple data formats, in the example above, standard data formats) Idkey: "id",//Set the property name corresponding to the ID when the simple data format is enabled PIDKEY: "PId"//settings Enable simple data  Format ParentID the corresponding property name, Ztree build the tree structure based on the ID and PID hierarchy}, check:{enable:true//Set whether checkbox check box is displayed, callback: {Onclick:onclick,//define node Click event callback function Onrightclick:onrightclick,//define node right-click event callback function Beforerename:beforerename ,//define a node to edit the callback function before success, generally used for node editing to determine whether the input of the node name is legitimate Ondblclick:ondblclick,//define node Double-click event callback function Oncheck:oncheck//Define node check box select or uncheck the event's callback function}, Async: {enable:true,//settings enable asynchronous Load type: ' Get ',//asynchronous Load Type: Post and get ContentType: "Application/json",//define parameter types for AJAX submission parameters, typically JSON format URL: "/design/get",//define Data Request path Autoparam: ["Id=id", "Name=name" ]//Define the name of the parameter at the time of submission, the = number before identifying the node genus, identifying the name of the parameter in the JSON data at the time of submission}};

 

It is important to note that the Ztree event callback section, basically each event corresponds to a beforexxx event, such as the OnClick event should have a Beforeonclick event, mainly to control whether the related events allow execution, If the Before event returns false, the corresponding related event is canceled.

1.2 Ztree data format
Each node of the Ztree is a TreeNode object, and the properties and methods often used by TreeNode objects are as follows:

TreeNode: {
    name,/  /node display text
    checked,//node checked, ztree configuration enabled checkbox when valid
    open,  //node expands
    icon,  / /node icon Iconopen,//Node
    expansion icon
    iconclose,///node folding icon
    ID,   //node identity attribute, corresponding to the simple data format when the Idkey corresponding property name, is not necessarily an ID, if the Idkey defined in setting: "ZId", then this is ZId
    pId,  //Node ParentID attribute, naming rule with ID
    children,//Get all child nodes of the node, Direct subordinate, to get all subordinate level nodes, need to write their own recursive to get
    isparent,//Determine whether the node is a parent node, generally used to judge only leaf nodes in order to carry out related operations, or delete when the following is a child node often used.
    GetPath ()//Gets the path of the node, that is, all the parent nodes, including themselves, this method returns an array that is typically used to create something like breadcrumbs a-->b-->c 
   }

Ztree data sources generally have standard data format, simple data format two, standard data format through the specified node Chidren attribute to build hierarchical relationship, and simple data format according to ID,PID attribute to build hierarchical relationship, we use relational database in application development, Generally, the simple data format is used.
Standard data format

 var nodes = [
 {name: ' Parent 1 ', children: [
  {name: ' child node 1 '},
  {name: ' child Node 2 '
 ]}
]; 

Simple data format

 var nodes = [
 {id:1, pid:0, Name: parent Node 1},
 {id:11, pid:1, Name: "Child node 1"},
 {id:12, pid:1, Name: "Child Node 2"}
]; 

Note Ztree's default configuration is not to enable simple data format, the simple data format must be in the setting for simple data format related configuration.

Common methods of 1.3 Ztree
The main operating methods of Ztree are as follows
Get Ztree object:var treeobj = $.fn.ztree.getztreeobj ("tree");
Add node:addnodes (parentnode,index,newnodes,isslient)

ParentNode: Specifies the parent node, if the root node is added, set parentnode to null

Index: The position inserted by the new node (starting from 0), index =-1, inserted at the end, this parameter can ignore

Newnodes: Need to increase the node data JSON object collection, the data only needs to meet the Ztree node data required attributes can

When Issilent:true, the parent node is not expanded after the node is added, and other values or default states are automatically expanded

  Tick or uncheck all nodes: checkallnodes (checked);
When the  checked parameter is true, all is checked, and when false, all uncheck.
  tick or uncheck individual nodes: Checknode (node, checked, checkedtypeflag,callbackflag);
 node: The node to be manipulated
 checked: Check for True, uncheck for false
 checketypeflag: To True indicates the linkage between the child nodes of the current node and the parent node, To false does not linkage
 callbackflag: Is true to indicate the callback function that executes the Beforeoncheck and Oncheck events, False does not perform
  edit node
 edit ( Node);  node is in edit state and must reference jquery.ztree.exedit extension.
  Expand or collapse all nodes: expandall (expand);
 expand is true to expand all nodes, or false to collapse all nodes.
  Find nodes based on node properties: Getnodesbyparam (Key,value, parentnode);
 key: Property name
 value: Property value
 parentnode: Whether to find under the specified node, NULL to represent the entire tree lookup.
  Get a set of nodes that are checked or not checked: getcheckednodes (checked);
 checked is true to get all the checked collection of nodes, false to all the node sets that are not checked,
  get the set of nodes where the input box tick state is changed: getchangecheckednodes ()

2 Common operations of Ztree
2.0 AJAX Request data and create Ztree

$ (function () {
   var setting = {     //here is configured according to your needs
    view: {
     selectedmulti:false
    },
    data:
     { Simpledata: {
      enable:true
     }
    },
    callback: {
     Onclick:ondesigntreeclick,
     Onrightclick : Onrightclick,
     beforerename:beforerename,      oncheck:oncheck
    }
   ;
   $.ajax ({
    type: "Get",
    URL: "/design/getdesigntreedata",     //ajax request address
     success:function (data) {
     $.fn.ztree.init ($ ("#treeZo"), setting, data);//Loading Date
    },
   })
  ;

The background code is as follows, you can return any data you want as needed, bind to Ztree, and then through the TreeNode. Attribute name to the corresponding value, implement some interface logic operation.

Public ActionResult Getdesigntreedata ()
  {
   var result = _designappservice.getdesigntreedata ();
   list<modeltreeviewmodel> treemodels = new list<modeltreeviewmodel> ();
   BOOL open = false;
   foreach (var. Designs)
   {
    if (design). ParentID = = guid.empty)
     open = true;
    else open = false;
    Treemodels.add (New Modeltreeviewmodel () {Id = design. Id.tostring (), PId = design. Parentid.tostring (), Name = design. Name, open = open, Data = design. Remarks?? "", ViewPoint = design. ViewPoint?? "", Checked = true});
   Return Json (Treemodels, jsonrequestbehavior.allowget);
  



2.1 Node Click action
The node Click event captures the unique identity Treeid of the event object E,ztree, and the currently selected node object TreeNode three parameters. Any attribute data contained in the TreeNode can be obtained according to the actual requirements and related operations

function OnClick (E, Treeid, TreeNode) {if
   (treenode.isparent)//If it is not a leaf node, end return
    ;
   alert (treenode.name); Gets the related attribute data on the current node, executes the related logic
  }; 

2.2 node check box event

In general, we will use Treeobj.getcheckednodes (true) directly, get all the selected nodes, and then traverse all the selected nodes for related operations, when faced with large amounts of data, this method of operation is not desirable, The Getchangecheckednodes () method can be used to get the set of nodes which are changed by the check state, and the value is processed accordingly for the node of state change.

function Oncheck () {var treeobj = $.fn.ztree.getztreeobj ("Treedemo");//Get Tree object var nodes = treeobj.getchangechecked  Nodes ();
   Get tick-state-changed node var designids = [];         var status = 0;         Defines the initial check state as not checked if (nodes[0].checked) status = 1;
   If the state changes the node to tick, the current operation is never checked and changed to checked.      $.each (nodes, function (I, item) {Designids.push (item.id);    Outputs the state-changed node ID to the array item.checkedold = item.checked; This is a critical phrase that will set the initial state of the node to the current state.
   Otherwise, each check operation gets the state to change the node only compared to the state of the tree initialization. }) $.ajax ({type: "Post", url: "/design/getrelationcomponentidsbydesigns", data: {"Designids": Designids}
     , Success:function (data) {realbimocx.batchaddsubclrinfobegin ();
       $.each (Data.result, function (I, item) {if (status = = 1)//Whether the node is checked or checked for the related logical operation according to the changed nodes.
      Realbimocx.addsubclrinfo (item, 255, 255, 0);
      else Realbimocx.addsubclrinfo (item, 0, 255, 0);
       if (i% = = 0) {realbimocx.batchaddsubclrinfoend (); Realbimocx.batchaddsUbclrinfobegin ();

    }) Realbimocx.batchaddsubclrinfoend ();

 }
   })
  };

2.3 Implement Ztree Right key additions and deletions to the operation
First define right-key pop-up panel

<div id= "Rmenu" style= "z-index:100;" >
  <ul>
   <li id= "M_add" onclick= "Addtreenode ();" > New node </li>
   <li id= "M_del" onclick= "Removetreenode ();" > Delete node </li>
   <li id= "M_edit" onclick= Edittreenode (); "style=" border-bottom:1px solid #cecece "> Edit Node </li><li id= "M_left" > Upgrade </li>
   <li id= "M_right" > Downgrade </li>
   <li id= "M_up" > Up </li>
   <li id= "M_down" style= "border-bottom:1px solid #cecece" > Move </li> <li id=
   "M _reset "onclick=" Resettree (); > Reset node </li> <li id= "M_open" onclick= Treeopen () "> Expand All </li> <li id=" m_stop "onclick="
   Treestop () "> Collect all </li>
  </ul>
</div>

Implement Ztree right-click event callback function

  Right-click the callback Functions function Onrightclick (event, Treeid, TreeNode) {$ ("#treeZo"). Hide (); if (!treenode &amp;&amp; event.target.tagName.toLowerCase ()!= "button" &amp;&amp; $ (event.target). Parents ("a").
    Length = = 0) {ztree.cancelselectednode (); Showrmenu ("Root", Event.clientx, Event.clienty);
    Displays the right key operator panel} else if (TreeNode &amp;&amp;!treenode.nor) {Ztree.selectnode (TreeNode) According to the mouse position;
   Showrmenu ("Node", Event.clientx, Event.clienty);
  $ ("#treeZo"). Show ();
   ///According to the node type, control the right mouse Action menu which available which unavailable function Showrmenu (type, x, y) {$ ("#rMenu ul"). Show ();
    if (type = = "Root") {$ ("#m_del"). Hide ();
    $ ("#m_edit"). Hide ();
    $ ("#m_left"). Hide ();
    $ ("#m_right"). Hide ();
    $ ("#m_up"). Hide ();
    $ ("#m_down"). Hide ();
   $ ("#m_add"). AddClass (' Mboder ');
    else {$ (' #m_del '). Show ();
    $ ("#m_edit"). Show ();
    $ ("#m_left"). Show ();
    $ ("#m_right"). Show ();
    $ ("#m_up"). Show ();
    $ ("#m_down"). Show ();
   $ ("#m_add"). Removeclass (' Mboder '); } rmenU.css ({"Top": Y + "px", "left": X + "px", "visibility": "Visible"});
  $ ("body"). Bind ("MouseDown", Onbodymousedown);
   ///To hide the right key panel function Hidermenu () {if (Rmenu) rmenu.css ({"Visibility": "Hidden"});
  $ ("body"). Unbind ("MouseDown", Onbodymousedown); //Click the other location of the page to hide the right button panel function Onbodymousedown (event) {if (!) ( Event.target.id = = "Rmenu" | |
   $ (event.target). Parents ("#rMenu"). Length &gt; 0)) {rmenu.css ({"Visibility": "Hidden"});

 }
  }

New node

  Add node
  function Addtreenode () {
   hidermenu ();
   var name = new Date (). GetTime (); The node name is generated using the timestamp to ensure that the node name uniquely
    var newNode = {
    name:name
   };
   if (ztree.getselectednodes () [0]) {
    newnode.checked = Ztree.getselectednodes () [0].checked;
    Newnode.pid = Ztree.getselectednodes () [0].id;
    Ztree.addnodes (Ztree.getselectednodes () [0], NewNode);
   } else {
    ztree.addnodes (null, NewNode);
   }
   var node = ztree.getnodebyparam ("name", name, NULL); The newly added node is
   ztree.selectnode (node);//Select the new Nodes
   Ztree.editname  . Let the newly added node be in edit state
  }

Edit Node

function Edittreenode () {
   var nodes = Ztree.getselectednodes ();//Get the selected node collection
   if (nodes && nodes.length > 0 {
    var parent = Nodes[0].getparentnode ();//Get the parent node of the selected node
    if (parent) {
     nodes[0].pid = parent.id;//If the section is selected The point parent node exists, setting the PID property value of the current node to the parent node's ID
    }
    ztree.editname (Nodes[0]);//Let the selected node be in the edit state
   Hidermenu ();  Hide right key panel
  };

Trigger event when node edit state leaves

  Edit and Save node
  function Beforerename (Treeid, TreeNode, NewName, iscancel) {
   if (newname.length = 0) {//node name judgment
    Alert ("cannot be empty.) ");
    return false;
   }
   else {
    $.ajax ({     //Data warehousing
     Type: "Post",
     URL: "/design/insertorupdate",
     data: {"DTO": {"Id": Treenode.id, "ParentID": Treenode.pid, "Name": NewName}},
     succes:function (data) {
      if (Data.result = "Faild" {
       Layeralert ("Save failed.") ");
       return false;
      }
      else {
       treenode.id = Data.result;//Assign the returned ID to the current node return
       true;
      }
  };

Delete node data

function Removetreenode () {
   hidermenu ();
   var nodes = Ztree.getselectednodes ();
   if (nodes && nodes.length > 0) {
    if (nodes[0].children && nodes[0].children.length > 0) {
     al ERT ("contains subordinates and cannot be deleted.) ");
    } else {
     if (confirm) (This action synchronizes the associated data to delete, confirm deletion?) = = = True) {
      $.ajax ({
       type: "Post",
       URL: "/design/delete",
       data: {"id": nodes[0].id},
       success : function (data) {
        if (Data.result = = "Success") {
         Ztree.removenode (nodes[0]);
        }
        else {
         alert ("Delete failed. ");
        }
       }
      });
     };
    }
   }
  };

2.4 Some summary
We typically use a tree control to authorize or correlate similar operations, usually first uncheck all, and then according to the selected data association to the tree control check box, in the large amount of data, about tens of thousands of data, all cancel Check + Check related nodes based on associated data this operation is slow through JS, this situation suggests that in the background, it is much faster to ztree the required data sources through association relationships, set the checked property for each data (corresponding tree node), and then reload the tree on the foreground page.

$.ajax ({
   type: "Get",
   URL: "/model/getrelationmodeltreedata?designid=" + treenode.id + "&t=" + New Date (), C3/>success:function (data) {
    //$.each (data.result, function (I, item) {
    //var node = Modeltree.getnodebyparam ( "id", item, NULL);
    Modeltree.checknode (node, true, true);
    //});
    $.fn.ztree.init ($ ("#treejian"), Setting1, Data.result); Reload instead, faster than JS cycle tick.
   }
  });

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.