最近在处理一个树形菜单,要做到异步加载、自动展开。可怎么搞都不行,要点击一下才能展开所有。
使用的zTree版本是v3.5.18。其实还是蛮简单的。话不多说,代码如下:
/** * 初始化菜单 */ 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++) { refreshTree(children[i]); } this.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); };
时间: 2024-10-21 18:36:28