Use of Ztree jQuery tree plugin (instance explanation)

Share Description:

The item requires a tree view form to display the data returned in the background; and implement the node to add the node information to the right of the right side; to be subsequent submit acquisition The Ztree plug-in that enables asynchronous loading node information, the facts also prove that this plugin is strong enough to meet almost all needs; when you just get in touch, you will have a sharing of people, combined with the official API document, and finally realize the function, now I will Summary of learning is also shared.

Effect introduction; except for Ztree default effect; use API to add some practical operations; including accordion effects; click on the parent node to expand the effect; click the Node text association check box effect; The number of primary nodes is displayed.

        
HTML part code

  
  • 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;} # uullt li {width: 100%; Height: 30px; list-style: none; line-height: 30px; margin- Bottom: 3px; Background-Color: # 00b6ba; Padding-Left: 10px; Box-Siting: 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

// Recursively found all nodes (non-parent nodes) Function getChildrennodes (Treenode.isparent) {var childrennodes = Treenode.children; if (childrennodes) {for (Var i = 0; i
 ("+ count +")  ");}, // Events when the parent node is expanded at ONEXPAND: Function (Event, TreeId, Treenode) {// ztree object var ztree = $ .fn .ztree.getztreeobj ("treedemo"); // Get clicked ID var nowid = Treenode.ID; // Get all node var allNodes = ztree.getnodes (); // Get Click the hierarchical var level of the node VAR level = Treenode.Level ; // Define a filter function; obtain the node hierarchical filter (node.Level == Treenode.level && node.isparent);} // obtained by the node hierarchical filter (node.Level == Treenode.level && Node.Ind);} //Get a collection of parent nodes of the node VAR SAMELEVES = Ztree.GETNODESBYFILTER (Filter); // Traverse the same set of collections collection for (var i = 0; i  
“); addli.find (“span”). TEXT (TREENODE.NAME); addli.animate ({Width: “100%”, Height: “30”}, 400) Addli.AppendTo ($ (“# Ulright”)); // Click on the node existent to the Connect field; Judgment the check box status Add to the right UL or delete if (TREENODE.CONNECT) {// Traverse the right LI, if the selected existence; Return FOR (VAR i = 0; i

“); addli.find (” span “); addli.animate ({Width:” 100% “, Height:” 30 “}, 400) addli.Appendto ($ (“# Ulright”));} // will be checked node background color to change $ (“# treedemo”). Find (“A [Title =” + Treenode.Name + “]”). CSS (” BackgroundcoLOR “,” # 00b6ba “); // Non-selected status, delete} else {// delete $ (” # Ulright “). Find (” li [title = “+ Treenode. Name + “]”). Animate ({Width: “0%”, Height: “0”}, 400, function () {$ (“# Ulright”). Find (“Li [Title =” + Treenode.name + ” ] “). Remove ();}) // Cancel this node background color $ (” # treedemo “). Find (” A [Title = “+ Treenode.name +”] “). CSS (” BackgroundColor “,” “);} // Select the parent node; get all sub-nodes (non-parent nodes), determine the check box status Add to the right UL or delete} else {// call recursive function; get all non-parent nodes Array Collection VAR AddNodesArray = getAllChildrennodes (Treenode, []); // is selected, add to the right ul if (Treenode.checked) {// Define Array VAR Rightliarray = []; $ (“# Ulright li “). Each (Function (i, v) {rightliarray.push ($ (v) .attr (” title “))}) Rightliarray = rightliarray.slice (1); // Traverse the checking array collection for (var i = 0; i “+ addnodesArray [i] +”

“); addli.animate ({Width: “100%”, Height: 30}, 400) Addli.AppendTO ($ (“# Ulright”));} // Modify the node background color to (“# treedemo”). Find (“A [” Title = “+ AddNodesArray [i] +”] “). CSS (” BackgroundColor “,” # 00b6ba “);} // is a non-selected state, delete} else {// traversal node, execute the delete operation for (VAR i = 0;
  Backstage PHP code; my pure front end, background code only simply write; < 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+"  <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 = $("
  • <rightLi.length;i++){ if($(rightLi[i]).attr("title") == treeNode.connect){ return; } } // 创建li 追加li var addLi = $("
  • Most of the JS code is annotated; the detailed API can be run in the server environment in the ztree official website. The official API document code is running in the server environment; <addNodesArray.length;i++){ //判断此节点是否在右侧ul内;不存在则加入 if(rightLiArray.indexOf(addNodesArray[i]) == -1){ //创建li 追加li var addLi = $("
  • <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); });
  • The use of this Ztree jquery tree plug-in (instance explanation) is the full content of Xiaobian sharing to everyone, hoping Give everyone a reference, and I hope everyoneSupport TUMI clouds.

    © Copyright Notice
    THE END
    Just support it if you like
    like0
    share
    comment Grab the couch

    Please log in to comment