首先,在适配目录树时,使用checkbox形式,配置代码如下:
看下效果:
这时的每个节点都处于一个可选的状态(但都未选中),但在实际项目中我们可能还会遇到另外两种情况:
1、根据后台返回的json,选中指定节点(此时所有的节点仍处于可编辑的状态);
代码如下:
var treeObj = $.fn.zTree.getZtreeObj("categoryTree");
for(var j = 0; j < zNodes.length; j++){
treeObj.checkNode(treeObj.getNodeByParam("id",zNodes[j].id),true);
}
zNodes是后台获取的json数据,其中包括 id、parentId、name、deep,形式如下:
2、根据json,选中指定节点,所有节点为不可操作状态。
代码如下:
/**获取树对象*/
var treeObj = $.fn.zTree.getZTreeObj("categoryTree");
/**获取所有节点*/
var nodes = treeObj.transformToArray(treeObj.getNodes());
for(var i = 0; i < nodes.length; i++){
for(var j = 0; j < zNodes.length; j++){
if(nodes[i] === treeObj.getNodeByParam("id",zNodes[j].dataAuthorityId)){
treeObj.checkNode(treeObj.getNodeByParam("id",zNodes[j].dataAuthorityId),true);
}
}
nodes[i].chkDisabled = true;
}
效果:
Tips:
实际项目中,有时需要把选中的节点以json的形式传给后台,既然要获取节点,那当然要从节点下手啦:
var json = [];
var treeObj=$.fn.zTree.getZTreeObj("categoryTree");
var nodes=treeObj.getCheckedNodes(true);
for(var i = 0; i < nodes.length; i++){
var obj = {};
obj.dataAuthorityId = nodes[i].id;
obj.parentId = nodes[i].pId;
obj.name = nodes[i].name;
obj.deep = nodes[i].deep;
json.push(obj);
}
json = JSON.stringfy(json); //要作为参数传给后台,别忘了序列化一下
看看我们得到了什么:
[{"dataAuthorityId":"00","parentId":null,"name":"京师目录体系","deep":"0"},{"dataAuthorityId":"gaozhong","parentId":"00","name":"高中","deep":"1"},{"dataAuthorityId":"gaozhong-shuxue","parentId":"gaozhong","name":"数学","deep":"2"},{"dataAuthorityId":"xiaoxue","parentId":"00","name":"小学","deep":"1"},{"dataAuthorityId":"xiaoxue-shuxue","parentId":"xiaoxue","name":"数学","deep":"2"},{"dataAuthorityId":"xiaoxue-yingyu","parentId":"xiaoxue","name":"英语","deep":"2"}]
水平有限,欢迎批评指正!