jquery ztree异步搜索

一、初始异步加载树

    初始化默认给出一个根结点,再结合异步加载的方式手动触发默认加载第一层,如图:

代码如下:
var treeSetting = {
  async: {
  enable: true, url:"xxx/demo.do?method=listByTree",
  dataType:"json",
  autoParam:["id=pid"]
  },
  view: {
  dblClickExpand: true,
  selectedMulti: false,
  expandSpeed: ($.browser.msie && parseInt($.browser.version)<=6)?"":"fast"
  },
  data: {
    simpleData: {
      enable:true,
      idKey: "id",
      pIdKey: "pid",
      rootPId: "root"
    }
  },
  callback: {
    onNodeCreated: zTreeOnNodeCreated
  }
};

//默认根结点
var rootNode = {"id":0, "pid":"root", "name":"商品分类", "open":true, "isParent":true};

$(document).ready(function(){
  var zTreeObj = $.fn.zTree.init($("#tree"), treeSetting, rootNode);
  var node = zTreeObj.getNodeByParam("id", 0, null);
  zTreeObj.reAsyncChildNodes(node, "refresh");
});

二、异步搜索叶子结点

    在使用JQuery ZTREE时可能要用到异步的方式模糊搜索叶子结点,如图:

    而如果只使用ZTREE自带的展开方法zTreeObj.expandNode只是会展开改结点,无法触发异步加载;这时候就必须手动调用异步加载的方法进行处理,解决思路如下:    
    通过在otherParam数组中设值的方式将搜索参数带到后台(无参数时必须将otherParam设为空数组否则一直会将前一次的参数带到后台);在结点创建完成后的回调函数onNodeCreated中进行手动异步加载。

代码如下:

function searchM() {
  var param = $.trim($("input[name='param']").val());
  var treeObj = $.fn.zTree.getZTreeObj("tree");
  var node = treeObj.getNodeByParam("id", 0, null);
  if(param != ""){
    param = encodeURI(encodeURI(param));
    treeObj.setting.async.otherParam=["param", param];
  }else {
    //搜索参数为空时必须将参数数组设为空
    treeObj.setting.async.otherParam=[];
  }
  treeObj.reAsyncChildNodes(node, "refresh");
}

function zTreeOnNodeCreated(event, treeId, treeNode) {
  var param = $.trim($("input[name='param']").val());
  var treeObj = $.fn.zTree.getZTreeObj("tree");
  //只有搜索参数不为空且该节点为父节点时才进行异步加载
  if(param != "" && treeNode.isParent){
    treeObj.reAsyncChildNodes(treeNode, "refresh");
  } 
};

 

posted @ 2017-04-07 11:40  岁月淡忘了谁  阅读(3693)  评论(3编辑  收藏  举报