首先,刚接触zTree时,一直研究异步加载时如何在前段js中配置一个固定的根节点,可是最终失败了,貌似zTree不支持这种做法,这点ext就比较灵活。所以,zTree做异步加载时,第一次在后台接收id的值会为null,此时需要对齐进行手动赋值,当展开根节点,第二次传参到后台时,接收的id就会有值。
言归正传,其实官方已经提供异步加载全部节点的示例(官方示例地址)。但是,官方的例子冗余代码太多,本示例是将官方示例简化后的版本。不足之处望大家指出。
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/component/ztree/css/zTreeStyle/zTreeStyle.css" /> <script type="text/javascript" src="<%=request.getContextPath()%>/component/ztree/js/jquery-1.4.4.min.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/component/ztree/js/jquery.ztree.core.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/component/ztree/js/jquery.ztree.excheck.js"></script>
<div style="border:solid 1px #a7b5bc; float:left; width:100%; height:100%; overflow-y:auto;"> <ul id="tree" class="ztree"></ul> </div>
<script type="text/javascript"> //初始化树 $(function() { $zTree = $.fn.zTree.init($("#tree"), $setting); //延迟展开根节点 setTimeout(function(){ var nodes = $zTree.getNodes(); if(nodes.length >0){ $zTree.expandNode($zTree.getNodes()[0], true, false, false); } },1000); }); //定义ztree树所需变量 var $zTree; var $zTreeFlag = true; var $setting = { async : { enable : true, url : "/baseplatform/auth/selectSysRoleUserTreeByPid.do", autoParam : ["id"], otherParam: {"srId":'${sysRole.srId}'} }, callback : { onAsyncSuccess : onAsyncSuccess }, data : { key : {name : "name"}, simpleData : {enable : true, idKey : "id", pIdKey : "pId", rootPId : -1} }, check: { enable: true } }; //每次加载节点触发的方法 function onAsyncSuccess(event, treeId, treeNode, msg) { //递归展开子节点 if(treeNode != undefined){ expandNodes(treeNode.children, "tree"); } } //递归展开子节点 function expandNodes(nodes, treeId) { if (!nodes) return; var zTree = $.fn.zTree.getZTreeObj(treeId); for (var i=0, l=nodes.length; i<l; i++) { zTree.expandNode(nodes[i], true, false, false); if (nodes[i].isParent && nodes[i].zAsync) { expandNodes(nodes[i].children, treeId); } } } </script>
如需转载请注明出处。