Sharing the use of zTree tree plug-in in jQuery
Sharing instructions:
The project needs to display the data returned by the background in the form of a tree view; and implement clicking on the node to add the node information to the ul on the right; wait for subsequent submissions to obtain and use; choose to be able to achieve asynchronous The zTree plug-in for loading node information has proven to be powerful enough to meet almost all needs. When I first came into contact with it, I read many people’s sharing and combined it with the official api documentation, I finally realized the function. Now I will share the summary of my learning. .
Effect introduction; In addition to the default effects of zTree, some practical operations are added using the API; including accordion effects; click on the parent node to expand the effect; click on the node text associated check box effect; display of the number of first-level child nodes Effect.
External resources introduced
1 <link rel="stylesheet" href="./zTree_v3-master/css/zTreeStyle/zTreeStyle.css"> 2 <script type="text/javascript" src="./jquery-1.9.1.js"></script> 3 <script type="text/javascript" src="./zTree_v3-master/js/jquery.ztree.all.min.js"></script>
html partial code
<div class="box"> <ul id="treeDemo" class="ztree"></ul> <ul id="ulright"> <li style="text-align: center;background-color: #ddd;border-bottom: 1px dashed">已选择</li> </ul> </div>
css code
ul,li,body{ margin: 0; padding: 0; } .ztree li span.node_name { font-size: 16px; } .box{ width: 500px; margin:10px auto; border:3px solid #ccc; padding: 20px; border-bottom: none; } #treeDemo{ width: 200px; display: inline-block; background-color: #f1f1f1; min-height: 200px; } #ulright{ width: 200px; margin-left: 50px; min-height: 200px; border:1px solid #ccc; display: inline-block; vertical-align: top; background-color: #eeeee8; } #ulright li{ width: 100%; height: 30px; list-style: none; line-height: 30px; margin-bottom: 3px; background-color: #00b6ba; padding-left: 10px; box-sizing: border-box; } /**/ .ztree li a.curSelectedNode{ background-color: transparent; border:#00b6ba; } .ztree li span.node_name{ font-size: 18px; line-height: 18px; color: #000; } .ztree li a{ padding: 5px; vertical-align: middle; } .ztree li a:hover{ text-decoration: none; } .ztree li span.button.chk{ margin: 9px 3px; }
js code
//递归找到所有节点(非父节点) function getAllChildrenNodes(treeNode,result){ if (treeNode.isParent) { var childrenNodes = treeNode.children; if (childrenNodes) { for (var i = 0; i < childrenNodes.length; i++) { if(!childrenNodes[i].children){ result.push(childrenNodes[i].name); } result = getAllChildrenNodes(childrenNodes[i], result); } } } return result; } var parames = 3; //zTree的所有配置 var setting = { //zTree 的唯一标识,初始化后,等于 用户定义的 zTree 容器的 id 属性值。 treeId:"", //zTree 容器的 jQuery 对象,主要功能:便于操作,内部参数,不可修改 treeObj:null, //异步请求数据配置;当父节点没有子节点时;点击此父节点会触发请求 async:{ //打开此功能 enable: true, url:"./zTreeDemoV9.0SimpleFromV10.0.php", type:"post", //发送的父级id的字段定义;如修改,遵循格式autoParam: ["id=parentId"] autoParam: ["id"], //其他需要提交的参数["name","topic","key","ss"]转换后格式为name=topic&key=ss otherParam:["json",parames || 1,"test","2"], dataType:"json", contentType: "application/x-www-form-urlencoded", //ajax请求后的数据预处理函数 dataFilter: function(treeId,parentNode,responseData){ for(var i=0;i<responseData.length;i++){ responseData[i] = JSON.parse(responseData[i]) } return responseData; } }, //数据配置 data: { simpleData: { enable: true, idKey: "id", //修改默认的ID为自己的id pIdKey: "pid", //修改默认父级ID为自己数据的父级id rootPId: 0 //根节点的父节点id } }, //视图配置 view: { //是否显示节点前的图标 showIcon: false, //节点上a标签的样式 fontCss: { } }, //选框配置 check: { //启用复选框 enable: true, //chkStyle:"radio" //复选框父子级选择联动设置 chkboxType: { "Y": "ps", "N": "ps" } }, //事件配置 callback: { //点击复选框之前的事件 beforeCheck:function(treeId, treeNode){//如果节点是父节点,并且勾选时没有子节点,则不允许勾选;针对父节点没有展开,则没有异步加载子节点,此情况禁止点击父节点全选子节点的操作 if(treeNode.isParent && !treeNode.children){ return false; } }, //回调错误事件 onAsyncError: function(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown){ alert("初始化节点数据失败,请稍后重试"); }, //回调成功事件 onAsyncSuccess: function(event, treeId, treeNode, resData){ var zTree = $.fn.zTree.getZTreeObj("treeDemo"); console.log("数据加载成功"); var count = (treeNode.children.length); //加载成功后;在节点后面显示此父节点下有几个一级子节点 $(".ztree").find("a[title="+treeNode.name+"]").find("span[class='node_name']").html(treeNode.name+"<span>("+count+")</span>"); }, //父节点展开时的事件 onExpand: function(event, treeId, treeNode){ //zTree对象 var zTree = $.fn.zTree.getZTreeObj("treeDemo"); //获取点击的id var nowId = treeNode.id; //获取所有节点 var allNodes = zTree.getNodes(); //获取点击节点的层级 var level = treeNode.level; //定义过滤函数;获取节点层级与点击节点层级相同并且为父节点的节点 function filter(node) { return (node.level == treeNode.level && node.isParent); } //获得点击节点同级的父节点的集合 var sameLevelNodes = zTree.getNodesByFilter(filter); //遍历同级节点集合 for(var i=0;i<sameLevelNodes.length;i++){ //将非被点击父节点收起;实现手风琴效果 if(sameLevelNodes[i].id != nowId){ zTree.expandNode(sameLevelNodes[i], false, true, true); } } }, //点击事件 onClick: function(e, treeId, treeNode, clickFlag) { //tree实例 var zTree = $.fn.zTree.getZTreeObj("treeDemo"); //点击文字关联复选框 //如果不是父节点,则关联,或者是父节点,但展开状态位true是,也关联; if(!treeNode.isParent || (treeNode.isParent && treeNode.open)){ zTree.checkNode(treeNode, !treeNode.checked, true);//点击文字关联复选框 } //点击文字展开当前节点 zTree.expandNode(treeNode, true, true, true); // zTree.reAsyncChildNodes(treeNode, "refresh");//强行异步加载(存在子节点也进行加载) //手风琴效果;直接调用onExpand zTree.setting.callback.onExpand(e, treeId, treeNode); //点击节点名称和勾选节点前面的复选框逻辑相同; //直接在onClick里面调用onCheck函数;并传入所需参数 zTree.setting.callback.onCheck(e, treeId, treeNode); }, //点击复选框事件 onCheck: function(e, treeId, treeNode) { //获取右侧ul内所有li标签;用于比较当前选择复选框在右侧是否一斤存在 var rightLi = $("#ulright").find("li"); //选中的是底层节点; if(!treeNode.isParent){ //选中状态,加入到右侧 if(treeNode.checked){ //遍历右侧li,如果选中的已经存在;return for(var i=0;i<rightLi.length;i++){ if($(rightLi[i]).attr("title") == treeNode.name){ return; } } // 创建li 追加li var addLi = $("<li title="+treeNode.name+"><span></span>"); addLi.find("span").text(treeNode.name); addLi.animate({ width:"100%", height:"30" },400) addLi.appendTo($("#ulright")); //如果点击的节点存在connect字段;判断复选框状态加入到右侧ul或删除 if(treeNode.connect){ //遍历右侧li,如果选中的已经存在;return for(var i=0;i<rightLi.length;i++){ if($(rightLi[i]).attr("title") == treeNode.connect){ return; } } // 创建li 追加li var addLi = $("<li title="+treeNode.connect+"><span></span>"); addLi.find("span").text(treeNode.connect); addLi.animate({ width:"100%", height:"30" },400) addLi.appendTo($("#ulright")); } //将被勾选的节点背景颜色更改 $("#treeDemo").find("a[title="+treeNode.name+"]").css("backgroundColor","#00b6ba"); //非选中状态,删除 }else{ //将右侧的次节点对应的li删除 $("#ulright").find("li[title="+treeNode.name+"]").animate({ width:"0%", height:"0" },400,function(){ $("#ulright").find("li[title="+treeNode.name+"]").remove(); }) //取消此节点的背景颜色 $("#treeDemo").find("a[title="+treeNode.name+"]").css("backgroundColor",""); } //选中的是父节点;获取所有子节点(非父节点),判断复选框状态加入到右侧ul或删除 }else{ //调用递归函数;获取所有非父级子节点数组集合 var addNodesArray = getAllChildrenNodes(treeNode,[]); //是选中状态,加入到右侧ul if(treeNode.checked){ //定义存储右侧li的数组 var rightLiArray = []; $("#ulright li").each(function(i,v){ rightLiArray.push($(v).attr("title")) }) rightLiArray = rightLiArray.slice(1); //遍历勾选的数组集合 for(var i=0;i<addNodesArray.length;i++){ //判断此节点是否在右侧ul内;不存在则加入 if(rightLiArray.indexOf(addNodesArray[i]) == -1){ //创建li 追加li var addLi = $("<li title="+addNodesArray[i]+"><span>"+addNodesArray[i]+"</span>"); addLi.animate({ width:"100%", height:30 },400) addLi.appendTo($("#ulright")); } //将节点背景颜色修改 $("#treeDemo").find("a[title="+addNodesArray[i]+"]").css("backgroundColor","#00b6ba"); } //是非选中状态,删除 }else{ //遍历节点,执行删除操作 for(var i=0;i<addNodesArray.length;i++){ $("#ulright").find("li[title="+addNodesArray[i]+"]").animate({ width:"0%", height:0 },function(){ $(this).css("display","none"); $(this).remove(); }) //还原背景颜色 $("#treeDemo").find("a[title="+addNodesArray[i]+"]").css("backgroundColor",""); } } } }, } }; //zTree的节点信息;可一次性全部加载;可试试异步请求 var zNodes = [{ name: "数据表",//名称 id: 4,//id,子元素的pid isParent:true,//是否为父节点,默认为false pid:0//父节点id;data中的rootPId; },{ name: "测试表", id: 1, isParent:true, pid:0 },{ name: "信息表", id: 2, isParent:true, pid:0 },{ name: "作废表", id: 3, isParent:true, pid:0 }]; $(document).ready(function() { //初始化zTree; zTree容器的jquery对象/ 配置/ 节点 $.fn.zTree.init($("#treeDemo"), setting, zNodes); });
Background php code; I am purely front-end, and I can only write simple background code;
<?php $pId = $_POST['id']; if($pId == 4){ $array = array('{"name":"数据表_一","id":"1_1","pid":"0"}','{"name":"数据表_二","id":"1_2","pid":"0"}','{"name":"数据表_三","id":"1_3","pid":"0"}','{"name":"数据表_四","id":"1_4","pid":"0"}','{"name":"数据表_五","id":"1_5","pid":"0"}'); }else if($pId == 1){ $array = array('{"name":"测试表_一","id":"2_1","pid":"1"}','{"name":"测试表_二","connect":"测试表_一","id":"2_2","pid":"1"}','{"name":"测试表_三","id":"2_3","pid":"1"}','{"name":"测试表_四","id":"2_4","pid":"1"}','{"name":"测试表_五","id":"2_5","pid":"1"}'); }else if($pId == 2){ $array = array('{"name":"信息表_一","id":"3_1","pid":"3"}','{"name":"信息表_二","id":"3_2","pid":"3"}','{"name":"信息表_三","id":"3_3","pid":"3"}','{"name":"信息表_四","id":"3_4","pid":"3"}','{"name":"信息表_五","id":"3_5","pid":"3"}','{"name":"信息表_五_一","id":"3_5_1","pid":"3_5"}','{"name":"信息表_五_二","id":"3_5_2","pid":"3_5"}','{"name":"信息表_三_一","id":"3_3_1","pid":"3_3"}','{"name":"信息表_三_二","id":"3_3_2","pid":"3_3"}','{"name":"信息表_三_三","id":"3_3_3","pid":"3_3"}'); }else if($pId == 3){ $array = array('{"name":"作废表_一","id":"4_1","pid":"3"}','{"name":"作废表_二","id":"4_2","pid":"3"}','{"name":"作废表_三","id":"4_3","pid":"3"}'); } echo json_encode($array);
Most of the js code has comments; detailed API can be viewed on the zTree official website and enter the official API document. The code needs to be run in a server environment;
Final chestnut renderings
The above is the detailed content of Sharing the use of zTree tree plug-in in jQuery. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

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

Quark Netdisk and Baidu Netdisk are very convenient storage tools. Many users are asking whether these two softwares are interoperable? How to share Quark Netdisk to Baidu Netdisk? Let this site introduce to users in detail how to save Quark network disk files to Baidu network disk. How to save files from Quark Network Disk to Baidu Network Disk Method 1. If you want to know how to transfer files from Quark Network Disk to Baidu Network Disk, first download the files that need to be saved on Quark Network Disk, and then open the Baidu Network Disk client. , select the folder where the compressed file is to be saved, and double-click to open the folder. 2. After opening the folder, click "Upload" in the upper left corner of the window. 3. Find the compressed file that needs to be uploaded on your computer and click to select it.

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the "Share to" option at the bottom, and then select the first "WeChat Moments" allows you to share content to WeChat Moments.

Recently, Baidu Netdisk Android client has ushered in a new version 8.0.0. This version not only brings many changes, but also adds many practical functions. Among them, the most eye-catching is the enhancement of the folder sharing function. Now, users can easily invite friends to join and share important files in work and life, achieving more convenient collaboration and sharing. So how do you share the files you need to share with your friends? Below, the editor of this site will give you a detailed introduction. I hope it can help you! 1) Open Baidu Cloud APP, first click to select the relevant folder on the homepage, and then click the [...] icon in the upper right corner of the interface; (as shown below) 2) Then click [+] in the "Shared Members" column 】, and finally check all

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

HP printers are essential printing equipment in many offices. Installing the printer driver on the computer can perfectly solve problems such as the printer being unable to connect. So how to install HP printer driver? The editor below will introduce you to two HP printer driver installation methods. The first method: download the driver from the official website 1. Search the HP China official website in the search engine, and in the support column, select [Software and Drivers]. 2. Select the [Printer] category, enter your printer model in the search box, and click [Submit] to find your printer driver. 3. Select the corresponding printer according to your computer system. For win10, select the driver for win10 system. 4. After downloading successfully, find it in the folder

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: <

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:

Many friends have their own wish-to-buy lists in the Meow Meow accounting software. What should I do if I want to share them with other friends? The following will introduce how to operate when sharing. 1. Click to open the Meow Meow accounting software on your mobile phone and click "My" in the lower right corner of the page to switch. 2. Find the "Shopping List" item on the personal center page and click to open it. 3. Next, enter the My Shopping List interface. Under the "Want to Buy List" tab, you will see the shopping list you have set. Click on the option you want to share to enter. 4. Click the three small dots icon side by side in the upper right corner of the list details page. 5. A window will pop up under the icon. Click and select the "Share List" item to share it with other friends.
