Home>

0 ztree introduction

The use of tree controls is essential during application development.ztree is a versatile "tree plugin" that relies on jquery. Excellent performance, flexible configuration, and the combination of multiple functions are the biggest advantages of ztree.

0.0 ztree features•The latest version of ztree divides the core code into functions,Unnecessary code can be left unloaded,For ordinary use, you only need to load the core jquery.ztree.core-3.5.js, you need to use the tick function to load jquery.ztree.excheck-3.5.min.js, you need to use the edit function to load jquery.ztree.exedit-3.5.min .js

•using lazy loading technology,Tens of thousands of nodes are easily loaded,It can basically do a spike even under ie6

•compatible with ie, firefox, chrome, opera, safari and other browsers

•support json data

Support static and ajax to load node data asynchronously

•Support arbitrary skin change/custom icons (rely on css)

•Support extremely flexible checkbox or radio selection

•Provide multiple event response callbacks

•Flexible editing (add/delete/modify/check) functions, you can drag nodes at willYou can also drag and drop multiple nodes

• Multiple tree instances can be generated simultaneously in one page

•Simple parameter configuration implementation,Flexible functions

0.1 ztree file introductionThe ztree downloaded from the ztree official website includes the following components

•metrostyle folder:ztree's metro style style related files (pictures and css style sheets).

•ztreestyle folder:ztree's standard style style folder (pictures and css style sheets)

•js file:ztree.all.js is a complete js library, you can simply load this file to implement all ztree functions, ztree.core, ztree.excheck, ztree.exedit, ztree.exhide segmentation,Corresponds to the basic function, check function, editing function, display function.

1 Basic use of ztree

1.0 ztree creationAdd js and css references to ztree in the page. Since ztree is based on jquery, jquery reference is required.

<! Doctype html>
<html>
<head>
 <title>ztree demo</title>
 <meta http-equiv="content-type" content="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={};//parameter configuration of ztree,Detailed later
  var znodes=[//data properties of ztree,Use standard json format here
  {
  name:"test1", open:true, children:[
  {name:"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 the ztree, the three parameters are containers at a time (the container classname of the ztree don't forget to set to "ztree") Parameter configuration, data source
 });
 </script>
</head>
<body>
 <div>
 <ul></ul>
 </div>
</body>
</html>

The results are as follows

1.1 ztree configurationThe configuration of ztree is in json format. According to the type of configuration, it is divided into view (visual interface related configuration), data (data related configuration), check (checkbox related configuration), and callback (callback functions for various events). Configuration), async (ztree asynchronous loading configuration), here are some configurations and instructions we often use,For other detailed configuration, please refer to the detailed introduction of ztree official api documentation.

var setting={
  view:{
  selectedmulti:true, //Set whether multiple nodes can be selected at the same time
  showicon:true, //Set whether to show the node icon
  showline:true, //Set whether to show the connection between nodes
  showtitle:true, //Set whether to display the title information of the node
  },  data:{
   simpledata:{
   enable:false, //Set whether to enable simple data format (ztree supports standard data format and simple data format,(The above example is the standard data format)
   idkey:"id", //Set the property name corresponding to id when simple data format is enabled
   pidkey:"pid" //Set the attribute name corresponding to the parentid when the simple data format is enabled,ztree builds tree structure based on id and pid hierarchy
  }
  },  check:{
  enable:true //Set whether to show the checkbox checkbox
  },  callback:{
  onclick:onclick, //Define the node click event callback function
  onrightclick:onrightclick, //Define a node right-click event callback function
  beforerename:beforerename, //Define the callback function before the node is re-edited successfully,Generally used to judge whether the entered node name is valid during node editing
  ondblclick:ondblclick, //Define the node double click event callback function
  oncheck:oncheck //Define the callback function of the node checkbox check or uncheck event
  },  async:{
  enable:true, //Set to enable asynchronous loading
  type:"get", //Asynchronous loading type:post and get
  contenttype:"application/json", //Define the parameter type of the ajax submission parameter,Generally in json format
  url:"/design/get", //Define the data request path
  autoparam:["id=id", "name=name"] //Define the name of the parameter when submitting,= Indicates the node attribute before the number,Identifies the name of the parameter in the json data at the time of submission
  }
 };

have to be aware of is,ztree event callback part,Basically, each event corresponds to a beforexxx event. For example, the onclick event corresponds to a beforeonclick event, which is mainly used to control whether related events are allowed to be executed.If the before event returns false, the corresponding event is canceled.

1.2 ztree data formatEach node of the ztree is a treenode object. The attributes and methods often used by the treenode object are as follows:

treenode:{
  name, //text displayed by the node
  checked, //whether the node is checked,ztree configuration works when checkbox is enabled
  open, //whether the node is expanded
  icon, //The icon of the node
  iconopen, //node expandable icon
  iconclose, //icon when node is collapsed
  id, //identity of the node,Corresponds to the attribute name corresponding to idkey when the simple data format is enabled,Not necessarily id, if idkey:"zid" defined in setting, then here is zid
  pid, //node parentid attribute, the same naming rules as id
  children, //Get all children nodes of this node,Subordinate directly
To get all subordinate nodes,Need to write recursively to get
  isparent, //Determine whether the node is the parent node,In general applications, it is usually necessary to determine that only leaf nodes can perform related operations.
Or when deleting, it is often used when there is a child node below.
  getpath () //Get the path of the node,I.e. all parent nodes,Including myself,This method returns an array,Usually used to create something like breadcrumb navigation a->b->c
  }

The data sources of ztree generally have two types:standard data format and simple data format.The standard data format constructs a hierarchical relationship by specifying the chidren attribute of a node,The simple data format builds hierarchical relationships based on id and pid attributes.We use relational databases in application development,Generally used are simple data formats.

Standard data format

var nodes=[
 {name:"parent node 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 that the default configuration of ztree is not to enable the simple data format,To use the simple data format, you must configure the simple data format in the setting.

1.3 Common methods of ztreeThe main operation method of ztree is introduced as follows

Get the ztree object:var treeobj=$.fn.ztree.getztreeobj ("tree");

Add nodes:addnodes (parentnode, index, newnodes, isslient)

parentnode:the specified parent node,If you add a root node,Please set parentnode to null

index:the position where the new node is inserted (starting from 0), when index=-1, it is inserted to the end,This parameter can be ignored

newnodes:a collection of node data json objects that need to be added,The data only needs to meet the required attributes of the node data of the ztree

issilent:true, the parent node is not expanded after the node is added,Other values ​​or default states are automatically expanded

Check or uncheck all nodes:checkallnodes (checked);

All checked when the checked parameter is true,When false, uncheck all.

Check or uncheck a single node:checknode (node, checked, checkedtypeflag, callbackflag);

node:the node to be operated on

checked:checked for true, unchecked for false

checketypeflag:If true, it means that the child node and parent node of the current node are checked.False

callbackflag:when true, it means to execute the callback function of beforeoncheck and oncheck event,False

Edit node

edit (node);put the node in edit state,You must reference the jquery.ztree.exedit extension.

Expand or collapse all nodes:expandall (expand);

expand to true is to expand all nodes,False is to collapse all nodes.

Find nodes based on node attributes:getnodesbyparam (key, value, parentnode);

key:attribute name

value:attribute value

parentnode:whether to search under the specified node,Null means that the entire tree is searched.

Get the set of checked or unchecked nodes:getcheckednodes (checked);

checked is true to get the set of all checked nodes,False to indicate all unchecked node collections

Get the set of nodes whose input box check state is changed:getchangecheckednodes ()

2 ztree common operations

2.0 ajax request data and create ztree

$(function () {
  var setting={//Configure here according to your own 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);//Load data
  },  });
 });

The background code is as follows,You can return any data i want on demand,Bind to the ztree, and then get the corresponding value through the treenode. Attribute name,Implement some interface logic operations.

public actionresult getdesigntreedata ()
 {
  var result=_designappservice.getdesigntreedata ();
  list<modeltreeviewmodel>treemodels=new list<modeltreeviewmodel>();
  bool open=false;
  foreach (var design in result.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 operationThe node click event captures the event object e, ztree's unique identifier treeid, and the currently selected node object treenode three parameters.Any attribute data contained in the treenode can be obtained according to actual needs,Perform related operations

function onclick (e, treeid, treenode) {
  if (treenode.isparent) //If it is not a leaf node,End
  return;
  alert (treenode.name);//Get related attribute data on the current node,Execute related logic
 };

2.2 Node checkbox events

In general, we will directly use treeobj.getcheckednodes (true);to get all selected nodes,Then iterate through all selected nodes for related operations,When facing large amounts of data,This method of operation is not desirable.You can use getchangecheckednodes () method to get the set of nodes whose check status is changed.The value is processed accordingly for the node whose state changes.

function oncheck () {
  var treeobj=$.fn.ztree.getztreeobj ("treedemo");//Get the tree object
  var nodes=treeobj.getchangecheckednodes ();//Get nodes whose check state has changed
  var designids=[];
  var status=0;//Define the initial check status as unchecked
  if (nodes [0] .checked)
  status=1;//If the status change node is checked,This indicates that the current operation is unchecked and checked.
  $.each (nodes, function (i, item) {
  designids.push (item.id);//Output node id of state change to array
   item.checkedold=item.checked;//This sentence is very important,Set the initial state of the node to the current state.
Otherwise, each time a check operation is performed to obtain the state change node, it will only be compared with the state initialized by the tree.
  })
  $.ajax ({
  type:"post",  url:"/design/getrelationcomponentidsbydesigns",  data:{"designids":designids},  success:function (data) {
   realbimocx.batchaddsubclrinfobegin ();
   $.each (data.result, function (i, item) {
   if (status == 1) //Relevant logic operations are performed here based on whether the changed node is checked or checked.
    realbimocx.addsubclrinfo (item, 255, 255, 0);
   else
    realbimocx.addsubclrinfo (item, 0, 255, 0);
   if (i%100 == 0) {
    realbimocx.batchaddsubclrinfoend ();
    realbimocx.batchaddsubclrinfobegin ();
   }
   })
   realbimocx.batchaddsubclrinfoend ();
  }
  })
 };

2.3 Realize right-click addition, deletion and modification of ztreeFirst define the right-click popup panel

<div>
 <ul>
  <li onclick="addtreenode ();">Add node</li>
  <li onclick="removetreenode ();">Remove node</li>
  <li onclick="edittreenode ();">Edit node</li><li>Upgrade</li>
  <li>Downgrade</li>
  <li>Move up</li>
  <li>Move down</li>
  <li onclick="resettree ();">reset node</li><li onclick="treeopen ()">expand all</li>
  <li onclick="treestop ()">Collapse all</li>
 </ul>
</div>

Implement ztree right click event callback function

//Right-click the callback function
 function onrightclick (event, treeid, treenode) {
  $("#treezo"). hide ();
  if (! treenode &&event.target.tagname.tolowercase ()!="button" && $(event.target) .parents ("a"). length == 0) {
  ztree.cancelselectednode ();
  showrmenu ("root", event.clientx, event.clienty);
  } else if (treenode &&! treenode.nor) {
  ztree.selectnode (treenode);
  showrmenu ("node", event.clientx, event.clienty);
  }
  $("#treezo"). show ();
 }
 //According to the node type,Control which right-click menus are available and which are not
 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);
 }
 //right panel
 function hidermenu () {
  if (rmenu) rmenu.css ({"visibility":"hidden"});
  $("body"). unbind ("mousedown", onbodymousedown);
 }
 //click elsewhere on the page to hide the right-click panel
 function onbodymousedown (event) {
  if (! (event.target.id == "rmenu" || $(event.target) .parents ("#rmenu"). length>0)) {
  rmenu.css ({"visibility":"hidden"});
  }
 }

Add node

//Add nodes
 function addtreenode () {
  hidermenu ();
  var name=new date (). gettime ();//Generate node name using timestamp,Keep node names unique
  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);//Get the newly added node
  ztree.selectnode (node);//Select the newly added node
  ztree.editname (node);//Let the newly added node be edited
 }

Edit node

function edittreenode () {
  var nodes=ztree.getselectednodes ();//Get selected node set
  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 selected node parent node exists,Set the pid attribute value of the current node to the id of the parent node
  }
  ztree.editname (nodes [0]);//Make selected nodes in edit state
  }
  hidermenu ();//Hide the right panel
 };

Event fired when node edit state leaves

//edit and save the node
 function beforerename (treeid, treenode, newname, iscancel) {
  if (newname.length == 0) {//node name judgment
  alert ("cannot be empty.
");
  return false;
  }
  else {
  $.ajax ({//data into the database
   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) {
   alert ("contains subordinates,Cannot be deleted.
");
  } else {
   if (confirm ("This operation will delete the associated data synchronously,Are you sure i want to delete it?") == 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 conclusionsWe usually use the tree control to authorize or associate similar operations.Generally, all of them will be unchecked first.Then select the check box of the tree control based on the selected data association.At large data volumes,About tens of thousands of data,Uncheck all + Check related nodes based on related data. This operation will be slow through JS.In this case, it is recommended to reorganize the data sources required by ztree through the association in the background.Set the checked property for each piece of data (corresponding to the tree node), and then reload the tree on the front page,This operation is much faster.

$.ajax ({
  type:"get",  url:"/model/getrelationmodeltreedata?designid =" + treenode.id + "&t =" + new date (),  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 loop checkbox.
  }
 });
  • Previous In-depth analysis of the wording of the search box
  • Next Upload file using JQuery plugin ajaxFileUpload in Aspnet MVC