jQuery Tree Control zTree Usage Detailed Explanation (I)

  • 2021-07-24 09:49:35
  • OfStack

1. Node fuzzy search function: After the search is successful, it will automatically highlight, locate and expand the searched nodes.

2. Asynchronous loading of nodes: 1. Load data when clicking Expand; 2. Load data when the node is selected.

The foreground code is as follows:

js:


<script type="text/javascript">
//ztree Settings 
var setting = {
view: {
fontCss: getFontCss
},
check: {
enable: true
},
data: {
simpleData: {
enable: true,
idKey: "id",
pIdKey: "pId",
rootPId: 0
}
},
async: {
enable: true,
url: "#{getStudentsJsonUrl}",
autoParam: ["id", "level"]
},
callback: {
beforeCheck: zTreeBeforeCheck,
onNodeCreated: zTreeOnNodeCreated,
beforeExpand: zTreeBeforeExpand
}
};

var reloadFlag = false; // Do you want to re-asynchronous request 
var checkFlag = true; // Whether to select 

// Before node expansion 
function zTreeBeforeExpand(treeId, treeNode) {
reloadFlag = false;
return true;
};

// After the node is created, 
function zTreeOnNodeCreated(event, treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj(treeId);
if (reloadFlag) {
if (checkFlag) {
zTree.checkNode(treeNode, true, true);
}
if (!treeNode.children) {
zTree.reAsyncChildNodes(treeNode, "refresh");
}
}
};

// Before selecting a node 
function zTreeBeforeCheck(treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj(treeId);
if (!treeNode.children) {
reloadFlag = true;
checkFlag = true;
zTree.reAsyncChildNodes(treeNode, "refresh");
}
return true;
}

// Page loading complete 
_run(function () {
require(['zTree/js/jquery.ztree.all-3.5'], function () {
$.ajax({
type: "POST",
url: "#{getStudentsJsonUrl}",
success: function (data) {
if (data && data.length != 0) { // If the result is not empty 
$.fn.zTree.init($("#tree"), setting, data);
}
else { // Search results are not available 

}
}
});
});

// Submit 
$("#inputSubmit").click(function () {
var zTree = $.fn.zTree.getZTreeObj("tree");
var nodes = zTree.getCheckedNodes(true);
var ids = "";
var names = "";
for (var i = 0; i < nodes.length; i++) { // Traverse the selected node collection 
if (!nodes[i].isParent) {
ids += nodes[i].id.replace("level" + nodes[i].level, "") + ",";
names += nodes[i].name + ",";
}
}
Simpo.ui.box.hideBox();
parent.$(".boxFrm").contents().find("#inputRange").val(names.substr(0, names.length - 1));
parent.$(".boxFrm").contents().find("#hidRange").val(ids.substr(0, ids.length - 1));
})
});

// Find Node 
var lastNodeList = [];
var lastKey;
function searchNode() {
var zTree = $.fn.zTree.getZTreeObj("tree");

var key = $.trim($("#inputSearchNode").val());
if (key != "" && key != lastKey) {
nodeList = zTree.getNodesByParamFuzzy("name", key);
for (var i = 0, l = lastNodeList.length; i < l; i++) { // Unhighlight the node collection of the last query 
lastNodeList[i].highlight = false;
zTree.updateNode(lastNodeList[i]);
}
zTree.expandAll(false); // Total contraction 
if (nodeList.length > 0) {
for (var i = 0, l = nodeList.length; i < l; i++) { // Traversing the collection of nodes found 
if (nodeList[i].getParentNode()) {
zTree.expandNode(nodeList[i].getParentNode(), true, false, false); // Expand its parent node 
}
nodeList[i].highlight = true;
zTree.updateNode(nodeList[i]);
}
}
zTree.refresh(); //  Is very important, otherwise the node state update is chaotic. 
lastNodeList = nodeList;
lastKey = key;
}
}

// Load data 
function loadData() {
var zTree = $.fn.zTree.getZTreeObj("tree");
var rootNodes = zTree.getNodes();
reloadFlag = true;
checkFlag = false;
for (var i = 0; i < rootNodes.length; i++) {
if (!rootNodes[i].children) {
zTree.reAsyncChildNodes(rootNodes[i], "refresh"); // Asynchronous loading 
}
}
}

// Total contraction 
function closeAll() {
var zTree = $.fn.zTree.getZTreeObj("tree");
if ($("#inputCloseAll").val() == " Total contraction ") {
zTree.expandAll(false);
$("#inputCloseAll").val(" Expand in full ")
}
else {
zTree.expandAll(true);
$("#inputCloseAll").val(" Total contraction ")
}
}

// Highlight style 
function getFontCss(treeId, treeNode) {
return (treeNode.highlight) ? { color: "#A60000", "font-weight": "bold"} : { color: "#333", "font-weight": "normal" };
}
</script>

html:


 <div style="width: 200px; height: 260px; overflow: auto; border: solid 1px #666;">
 <ul id="tree" class="ztree">
 </ul>
 </div>

Background code (background returns Json data):


 public void SelStudent()
 {
 set("getStudentsJsonUrl", to(GetStudentsJson));
 }

 public void GetStudentsJson()
 {
 List<Dictionary<string, string>> dicList = new List<Dictionary<string, string>>();

 string level = ctx.Post("level");
 string id = ctx.Post("id");
 if (strUtil.IsNullOrEmpty(id))
 {
 #region  Load class 
 // Get the current logged-in user 
 Sys_User user = AdminSecurityUtils.GetLoginUser(ctx);
 // Gets the teacher associated with the current user 
 Edu_Teacher teacher = edu_TeacService.FindByUserId(user.Id);
 // Get class collection 
 List<Edu_ClaNameFlow> list = edu_ClaNameFlowService.GetListByTeacherId(teacher.Id);
 foreach (Edu_ClaNameFlow item in list)
 {
  Dictionary<string, string> dic = new Dictionary<string, string>();
  dic.Add("id", "level0" + item.Calss.Id.ToString());
  dic.Add("pId", "0");
  dic.Add("name", item.Gra.Name + item.Calss.Name);
  dic.Add("isParent", "true");
  dicList.Add(dic);
 }
 #endregion
 }
 else
 {
 if (level == "0")
 {
  // Load students 
  List<Edu_Student> list = edu_StudService.GetListByClassId(id.Replace("level0", ""));
  foreach (Edu_Student item in list)
  {
  Dictionary<string, string> dic = new Dictionary<string, string>();
  dic.Add("id", "level1" + item.Id.ToString());
  dic.Add("pId", id);
  dic.Add("name", item.Name);
  dic.Add("isParent", "false");
  dicList.Add(dic);
  }
 }
 }

 echoJson(dicList);
 }

For more information on the ztree control, refer to the topic "jQuery plug-in ztree usage summary."


Related articles: