### zTree Initialization API
Source: https://github.com/ztree/ztree_v3/blob/master/api/en/fn.zTree.init.html
This section details the initialization of a zTree instance using the $.fn.zTree.init() method.
```APIDOC
## $.fn.zTree.init(obj, zSetting, zNodes)
### Description
This method is used to create a zTree.
### Method
JavaScript Function
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **obj** (jQuery Object) - DOM Container for zTree
* **zSetting** (JSON) - zTree's configuration data.
* **zNodes** (Array(JSON) / JSON) - zTree's node data.
### Request Example
```javascript
var zTreeObj, setting = {
view: {
selectedMulti: false
}
}, zTreeNodes = [
{"name":"Site Map", open:true, children: [
{ "name":"google", "url":"http://www.google.com", "target":"_blank"},
{ "name":"baidu", "url":"http://baidu.com", "target":"_blank"},
{ "name":"sina", "url":"http://www.sina.com.cn", "target":"_blank"}
]
}
];
$(document).ready(function(){
zTreeObj = $.fn.zTree.init($("#tree"), setting, zTreeNodes);
});
```
### Response
#### Success Response (200)
* **zTree object** (JSON) - An object that provides methods to operate the zTree.
```
--------------------------------
### Install zTree v3 using npm
Source: https://github.com/ztree/ztree_v3/blob/master/README.md
This command installs the zTree v3 library using the npm package manager. It is a common way to add front-end libraries to a project for use in web development.
```bash
npm install @ztree/ztree_v3
```
--------------------------------
### zTree onAsyncSuccess Example with Alert
Source: https://github.com/ztree/ztree_v3/blob/master/api/cn/setting.callback.onAsyncSuccess.html
This example demonstrates how to use the onAsyncSuccess callback to display an alert with the message received from the asynchronous data load. It requires the zTree core JavaScript library and jQuery.
```javascript
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
alert(msg);
};
var setting = {
callback: {
onAsyncSuccess: zTreeOnAsyncSuccess
}
};
......
```
--------------------------------
### zTree onRightClick Callback Example (JavaScript)
Source: https://github.com/ztree/ztree_v3/blob/master/api/cn/setting.callback.onRightClick.html
This example demonstrates how to define and use the zTree onRightClick callback function. It shows how to access node information (tId and name) and trigger an alert. The callback is configured within the zTree settings object.
```javascript
function zTreeOnRightClick(event, treeId, treeNode) {
alert(treeNode ? treeNode.tId + ", " + treeNode.name : "isRoot");
};
var setting = {
callback: {
onRightClick: zTreeOnRightClick
}
};
......
```
--------------------------------
### zTree onMouseDown Callback Example
Source: https://github.com/ztree/ztree_v3/blob/master/api/cn/setting.callback.onMouseDown.html
This JavaScript example demonstrates how to define and use the zTree onMouseDown callback function. It shows how to access node information and alerts the tId and name of the clicked node. The callback is registered within the zTree's setting object.
```javascript
function zTreeOnMouseDown(event, treeId, treeNode) {
alert(treeNode ? treeNode.tId + ", " + treeNode.name : "isRoot");
};
var setting = {
callback: {
onMouseDown: zTreeOnMouseDown
}
};
......
```
--------------------------------
### ZTREE Reset and Initialization
Source: https://github.com/ztree/ztree_v3/blob/master/demo/en/super/asyncForAll.html
Resets the zTree to its initial state, clearing any asynchronous loading flags and re-initializing the tree with the defined settings. This is useful for starting over or applying changes.
```javascript
function reset() {
if (!check()) {
return;
}
asyncForAll = false;
goAsync = false;
$("#demoMsg").text("");
$.fn.zTree.init($("#treeDemo"), setting);
}
```
--------------------------------
### zTree onExpand Callback Example with jQuery
Source: https://github.com/ztree/ztree_v3/blob/master/api/cn/setting.callback.onExpand.html
This JavaScript snippet demonstrates how to implement the `onExpand` callback function for zTree. It shows how to define the callback to receive event, treeId, and treeNode arguments, and an example of setting the callback within the zTree configuration. It depends on jQuery and the zTree core JavaScript library.
```javascript
function zTreeOnExpand(event, treeId, treeNode) {
alert(treeNode.tId + ", " + treeNode.name);
};
var setting = {
callback: {
onExpand: zTreeOnExpand
}
};
......
```
--------------------------------
### Initialize ZTREE with Drag and Drop Enabled (JavaScript)
Source: https://github.com/ztree/ztree_v3/blob/master/demo/en/exedit/drag.html
Initializes the ZTREE component with drag and drop editing enabled. It configures various drag and drop behaviors such as copying, moving, and drop positions, and sets up event listeners for these configurations.
```javascript
var setting = {
edit: {
enable: true,
showRemoveBtn: false,
showRenameBtn: false
},
data: {
simpleData: {
enable: true
}
},
callback: {
beforeDrag: beforeDrag,
beforeDrop: beforeDrop
}
};
var zNodes = [
{ id: 1, pId: 0, name: "can drag 1", open: true },
{ id: 11, pId: 1, name: "can drag 1-1" },
{ id: 12, pId: 1, name: "can drag 1-2", open: true },
{ id: 121, pId: 12, name: "can drag 1-2-1" },
{ id: 122, pId: 12, name: "can drag 1-2-2" },
{ id: 123, pId: 12, name: "can drag 1-2-3" },
{ id: 13, pId: 1, name: "can't drag 1-3", open: true, drag: false },
{ id: 131, pId: 13, name: "can't drag 1-3-1", drag: false },
{ id: 132, pId: 13, name: "can't drag 1-3-2", drag: false },
{ id: 133, pId: 13, name: "can drag 1-3-3" },
{ id: 2, pId: 0, name: "can drag 2", open: true },
{ id: 21, pId: 2, name: "can drag 2-1" },
{ id: 22, pId: 2, name: "can't drop 2-2", open: true, drop: false },
{ id: 221, pId: 22, name: "can drag 2-2-1" },
{ id: 222, pId: 22, name: "can drag 2-2-2" },
{ id: 223, pId: 22, name: "can drag 2-2-3" },
{ id: 23, pId: 2, name: "can drag 2-3" }
];
function beforeDrag(treeId, treeNodes) {
for (var i = 0, l = treeNodes.length; i < l; i++) {
if (treeNodes[i].drag === false) {
return false;
}
}
return true;
}
function beforeDrop(treeId, treeNodes, targetNode, moveType) {
return targetNode ? targetNode.drop !== false : true;
}
function setCheck() {
var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
isCopy = $("#copy").attr("checked"),
isMove = $("#move").attr("checked"),
prev = $("#prev").attr("checked"),
inner = $("#inner").attr("checked"),
next = $("#next").attr("checked");
zTree.setting.edit.drag.isCopy = isCopy;
zTree.setting.edit.drag.isMove = isMove;
showCode(1, ['setting.edit.drag.isCopy = ' + isCopy, 'setting.edit.drag.isMove = ' + isMove]);
zTree.setting.edit.drag.prev = prev;
zTree.setting.edit.drag.inner = inner;
zTree.setting.edit.drag.next = next;
showCode(2, ['setting.edit.drag.prev = ' + prev, 'setting.edit.drag.inner = ' + inner, 'setting.edit.drag.next = ' + next]);
}
function showCode(id, str) {
var code = $("#code" + id);
code.empty();
for (var i = 0, l = str.length; i < l; i++) {
code.append("
" + str[i] + "
");
}
}
$(document).ready(function() {
$.fn.zTree.init($("#treeDemo"), setting, zNodes);
setCheck();
$("#copy").bind("change", setCheck);
$("#move").bind("change", setCheck);
$("#prev").bind("change", setCheck);
$("#inner").bind("change", setCheck);
$("#next").bind("change", setCheck);
});
//-->
```
--------------------------------
### Configure Static Async URL with zTree
Source: https://github.com/ztree/ztree_v3/blob/master/api/cn/setting.async.url.html
Sets a fixed URL for asynchronously fetching tree nodes. This configuration is used when `setting.async.enable` is true. The URL can include parameters that will be submitted via GET. Ensure proper URL encoding for parameters.
```javascript
var setting = {
async: {
enable: true,
url: "nodes.php",
autoParam: ["id", "name"]
}
};
......
```
--------------------------------
### Initialize ZTree with Basic Settings
Source: https://github.com/ztree/ztree_v3/blob/master/demo/en/index.html
This snippet demonstrates the initialization of a ZTree instance using basic view and data settings. It configures the tree to use simple data format and enables basic line display. The `beforeClick` callback is set to handle node clicks, expanding parent nodes or loading content for leaf nodes.
```javascript
var zTree;
var demoIframe;
var setting = {
view: {
dblClickExpand: false,
showLine: true,
selectedMulti: false
},
data: {
simpleData: {
enable: true,
idKey: "id",
pIdKey: "pId",
rootPId: ""
}
},
callback: {
beforeClick: function(treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj("tree");
if (treeNode.isParent) {
zTree.expandNode(treeNode);
return false;
} else {
demoIframe.attr("src", treeNode.file + ".html");
return true;
}
}
}
};
```
--------------------------------
### Get Selected Node's Expansion State
Source: https://github.com/ztree/ztree_v3/blob/master/api/cn/treeNode.open.html
This example demonstrates how to retrieve the current expansion state (open or collapsed) of a selected node in a ztree. It depends on the jquery.ztree.core library and assumes a tree with the ID 'tree' exists. The input is the ztree object and selected nodes, and the output is a boolean indicating the node's open state.
```javascript
var treeObj = $.fn.zTree.getZTreeObj("tree");
var sNodes = treeObj.getSelectedNodes();
if (sNodes.length > 0) {
var isOpen = sNodes[0].open;
console.log("Node is open: " + isOpen);
}
```
--------------------------------
### zTree v3: Cancel First Selected Node (JavaScript)
Source: https://github.com/ztree/ztree_v3/blob/master/api/cn/zTreeObj.cancelSelectedNode.html
This example shows how to cancel the selection of only the first selected node in a zTree. It first gets the zTree object, then retrieves the array of selected nodes using getSelectedNodes(). If there are any selected nodes, it calls cancelSelectedNode with the first node in the array. This is useful for scenarios where only a single deselection is needed.
```javascript
var treeObj = $.fn.zTree.getZTreeObj("tree");
var nodes = treeObj.getSelectedNodes();
if (nodes.length>0) {
treeObj.cancelSelectedNode(nodes[0]);
}
```
--------------------------------
### ZTREE Configuration and Initialization (JavaScript)
Source: https://github.com/ztree/ztree_v3/blob/master/demo/cn/super/asyncForAll.html
Configures ZTree settings for asynchronous loading, including the URL for fetching nodes, parameters for asynchronous requests, and callback functions for handling asynchronous events. It initializes the ZTree with these settings.
```javascript
var demoMsg = {
async: "正在进行异步加载,请等一会儿再点击...",
expandAllOver: "全部展开完毕",
asyncAllOver: "后台异步加载完毕",
asyncAll: "已经异步加载完毕,不再重新加载",
expandAll: "已经异步加载完毕,使用 expandAll 方法"
};
var setting = {
async: {
enable: true,
url: "../asyncData/getNodes.php",
autoParam: ["id", "name=n", "level=lv"],
otherParam: {"otherParam": "zTreeAsyncTest"},
dataFilter: filter,
type: "get"
},
callback: {
beforeAsync: beforeAsync,
onAsyncSuccess: onAsyncSuccess,
onAsyncError: onAsyncError
}
};
function filter(treeId, parentNode, childNodes) {
if (!childNodes) return null;
for (var i = 0, l = childNodes.length; i < l; i++) {
childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
}
return childNodes;
}
function beforeAsync() {
curAsyncCount++;
}
function onAsyncSuccess(event, treeId, treeNode, msg) {
curAsyncCount--;
if (curStatus == "expand") {
expandNodes(treeNode.children);
} else if (curStatus == "async") {
asyncNodes(treeNode.children);
}
if (curAsyncCount <= 0) {
if (curStatus != "init" && curStatus != "") {
$("#demoMsg").text((curStatus == "expand") ? demoMsg.expandAllOver : demoMsg.asyncAllOver);
asyncForAll = true;
}
curStatus = "";
}
}
function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
curAsyncCount--;
if (curAsyncCount <= 0) {
curStatus = "";
if (treeNode != null) asyncForAll = true;
}
}
var curStatus = "init", curAsyncCount = 0, asyncForAll = false, goAsync = false;
$(document).ready(function() {
$.fn.zTree.init($("#treeDemo"), setting);
$("#expandAllBtn").bind("click", expandAll);
$("#asyncAllBtn").bind("click", asyncAll);
$("#resetBtn").bind("click", reset);
});
```
--------------------------------
### Get All zTree Nodes using jQuery
Source: https://github.com/ztree/ztree_v3/blob/master/api/en/zTreeObj.getNodes.html
This snippet demonstrates how to retrieve all nodes from a zTree instance using jQuery. It first gets the zTree object associated with an HTML element and then calls the getNodes() method to fetch all root nodes. Note that for fully traversing all nodes, recursion or the transformToArray() method might be necessary, and asynchronously loaded nodes cannot be retrieved.
```javascript
var treeObj = $.fn.zTree.getZTreeObj("tree");
var nodes = treeObj.getNodes();
```
--------------------------------
### Get Parent Node of Selected Node using ztree.js and jQuery
Source: https://github.com/ztree/ztree_v3/blob/master/api/en/treeNode.getParentNode.html
This code snippet demonstrates how to get the parent node of the first selected node in a zTree. It first retrieves the zTree object using its ID, then gets the selected nodes. If there are selected nodes, it calls getParentNode() on the first selected node. This function depends on jQuery and the ztree.core.js library.
```javascript
var treeObj = $.fn.zTree.getZTreeObj("tree");
var sNodes = treeObj.getSelectedNodes();
if (sNodes.length > 0) {
var node = sNodes[0].getParentNode();
}
```
--------------------------------
### Initialize zTree with Basic Settings
Source: https://github.com/ztree/ztree_v3/blob/master/api/en/fn.zTree.init.html
Demonstrates the initialization of a zTree using jQuery. This snippet requires jQuery and the zTree core JavaScript library. It takes a jQuery object representing the DOM container, a settings object, and an array of node data as input to create an interactive tree structure.
```html
ZTREE DEMO