最近在處理一個樹形菜單,要作到異步加載、自動展開。可怎麼搞都不行,要點擊一下才能展開全部。node
使用的zTree版本是v3.5.18。其實仍是蠻簡單的。話很少說,代碼以下:json
/** * 初始化菜單 */ var initTree = function(treeId) { var settings = { treeId: treeId, async: { enable: true, type: 'post', dataType: 'json', url: 'menu/getMenusByParentId', // 查詢子菜單參數,傳父節點id、以及父節點是否爲葉子。葉子節點將再也不查詢,提升性能 autoParam: ["id=parent_id", "is_leaf"], dataFilter: function(treeId, parentNode, responseData) { if(responseData) { for(var i = 0, length = responseData.length; i < length; i++) { var node = responseData[i]; if(node.is_leaf == 0) {//節點的isParent=true,纔會異步加載子節點 node.isParent = true; } } } return responseData; } }, callback: { onAsyncSuccess: function(event, treeId, treeNode, msg){ // 此回調函數可逐級異步展開子節點 if(treeNode.isParent == true && treeNode.children && treeNode.children.length > 0) { var children = treeNode.children; for(var i = 0, length = children.length; i < length; i++) { zTreeObj.reAsyncChildNodes(children[i], "refresh", false); } zTreeObj.expandNode(treeNode, true); } } } }; var rootNode = {name:"菜單", murl:'', isParent: true, open:false, id: 0, is_leaf: 0}; var zTreeObj = $.fn.zTree.init($("#"+treeId), settings, rootNode); // 異步加載樹.這裏要注意:直接傳rootNode異步刷新樹,將沒法展開rootNode。 // 要經過以下方式獲取根節點。false參數展開本節點 zTreeObj.reAsyncChildNodes(zTreeObj.getNodes()[0], "refresh", false); };