一、初始非同步載入樹
初始化預設給一個根結點,再結合非同步載入的方式手動觸發預設載入第一層,如圖:
程式碼如下:
var treeSetting = { async: { enable: true, <a href="http://my.oschina.net/wealpan/admin/"xxx/demo.do?method=listByTree" rel="nofollow">url:"xxx/demo.do?method=listByTree</a>", 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 <span></span><span></span>= $.tr<span></span>im($("input[name='param']").val()); var treeObj = $.fn.zTree.getZTreeObj("tree"); //只有搜索参数不为空且该节点为父节点时才进行异步加载 if(param != "" && treeNode.isParent){ treeObj.reAsyncChildNodes(treeNode, "refresh"); } };
以上就是關於jquery ztree非同步搜尋的全部內容,希望對大家的學習有所幫助。