


jquery zTree asynchronous loading, fuzzy search simple example sharing_jquery
The example in this article explains the basic usage of jquery zTree tree plug-in. The specific content is as follows
1. Node fuzzy search function: After the search is successful, the searched nodes will be automatically highlighted, positioned, and expanded.
2. Asynchronous loading of nodes: 1. Load data when you click to expand; 2. Load data when a node is selected.
The frontend code is as follows:
<script type="text/javascript"> //ztree设置 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; //是否重新异步请求 var checkFlag = true; //是否选中 //节点展开前 function zTreeBeforeExpand(treeId, treeNode) { reloadFlag = false; return true; }; //节点创建后 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"); } } }; //选中节点前 function zTreeBeforeCheck(treeId, treeNode) { var zTree = $.fn.zTree.getZTreeObj(treeId); if (!treeNode.children) { reloadFlag = true; checkFlag = true; zTree.reAsyncChildNodes(treeNode, "refresh"); } return true; } //页面加载完成 _run(function () { require(['zTree/js/jquery.ztree.all-3.5'], function () { $.ajax({ type: "POST", url: "#{getStudentsJsonUrl}", success: function (data) { if (data && data.length != 0) { //如果结果不为空 $.fn.zTree.init($("#tree"), setting, data); } else { //搜索不到结果 } } }); }); //提交 $("#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++) { //遍历选择的节点集合 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)); }) }); //查找节点 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++) { //上次查询的节点集合取消高亮 lastNodeList[i].highlight = false; zTree.updateNode(lastNodeList[i]); } zTree.expandAll(false); //全部收缩 if (nodeList.length > 0) { for (var i = 0, l = nodeList.length; i < l; i++) { //遍历找到的节点集合 if (nodeList[i].getParentNode()) { zTree.expandNode(nodeList[i].getParentNode(), true, false, false); //展开其父节点 } nodeList[i].highlight = true; zTree.updateNode(nodeList[i]); } } zTree.refresh(); // 很重要,否则节点状态更新混乱。 lastNodeList = nodeList; lastKey = key; } } //加载数据 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"); //异步加载 } } } //全部收缩 function closeAll() { var zTree = $.fn.zTree.getZTreeObj("tree"); if ($("#inputCloseAll").val() == "全部收缩") { zTree.expandAll(false); $("#inputCloseAll").val("全部展开") } else { zTree.expandAll(true); $("#inputCloseAll").val("全部收缩") } } //高亮样式 function getFontCss(treeId, treeNode) { return (treeNode.highlight) ? { color: "#A60000", "font-weight": "bold"} : { color: "#333", "font-weight": "normal" }; } </script>
<div style="width: 200px; height: 260px; overflow: auto; border: solid 1px #666;"> <ul id="tree" class="ztree"> </ul> </div>
Background code (Json data returned in the background):
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 加载班级 //获取当前登录用户 Sys_User user = AdminSecurityUtils.GetLoginUser(ctx); //获取当前用户关联的老师 Edu_Teacher teacher = edu_TeacService.FindByUserId(user.Id); //获取班级集合 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") { //加载学生 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); }
3. After the zTree tree is refreshed based on cookies, the expanded state remains unchanged
1. In addition to the JS that references jQuery and zTree, the JS that references cookies:
2. JS code:
$(function () { //ztree设置 var setting = { data: { simpleData: { enable: true, idKey: "id", pIdKey: "pId", rootPId: null } }, callback: { onExpand: onExpand, onCollapse: onCollapse } }; $.ajax({ type: "POST", url: "/Tech/TemplateTypeManage/GetData", success: function (data) { if (data && data.length != 0) { $.fn.zTree.init($("#tree"), setting, data); var treeObj = $.fn.zTree.getZTreeObj("tree"); var cookie = $.cookie("z_tree" + window.location); if (cookie) { z_tree = JSON2.parse(cookie); for (var i = 0; i < z_tree.length; i++) { var node = treeObj.getNodeByParam('id', z_tree[i]) treeObj.expandNode(node, true, false) } } } } }); });//end $ function onExpand(event, treeId, treeNode) { var cookie = $.cookie("z_tree" + window.location); var z_tree = new Array(); if (cookie) { z_tree = JSON2.parse(cookie); } if ($.inArray(treeNode.id, z_tree) < 0) { z_tree.push(treeNode.id); } $.cookie("z_tree" + window.location, JSON2.stringify(z_tree)) } function onCollapse(event, treeId, treeNode) { var cookie = $.cookie("z_tree" + window.location); var z_tree = new Array(); if (cookie) { z_tree = JSON2.parse(cookie); } var index = $.inArray(treeNode.id, z_tree); z_tree.splice(index, 1); for (var i = 0; i < treeNode.children.length; i++) { index = $.inArray(treeNode.children[i].id, z_tree); if (index > -1) z_tree.splice(index, 1); } $.cookie("z_tree" + window.location, JSON2.stringify(z_tree)) }
The above is a simple example explanation of asynchronous loading and fuzzy search of the tree plug-in zTree. I hope it will be helpful to everyone's learning.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Delegation is a type-safe reference type used to pass method pointers between objects to solve asynchronous programming and event handling problems: Asynchronous programming: Delegation allows methods to be executed in different threads or processes, improving application responsiveness. Event handling: Delegates simplify event handling, allowing events such as clicks or mouse movements to be created and handled.

Although HTML itself cannot read files, file reading can be achieved through the following methods: using JavaScript (XMLHttpRequest, fetch()); using server-side languages (PHP, Node.js); using third-party libraries (jQuery.get() , axios, fs-extra).

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:

目录1:basename()2:copy()3:dirname()4:disk_free_space()5:disk_total_space()6:file_exists()7:file_get_contents()8:file_put_contents()9:filesize()10:filetype()11:glob()12:is_dir()13:is_writable()14:mkdir()15:move_uploaded_file()16:parse_ini_file()17:

To include an external JS file in HTML, use the <script> tag and specify the URL of the file to load. You can also specify type, defer, or async attributes to control how loading and execution occur. Typically, the <script> tag should be placed at the bottom of the <body> section to avoid blocking page rendering.
