zTree树插件使用方法及自定义控件实践
zTree简介:
zTree 是一个依靠 jQuery 实现的多功能 “树插件”。优异的性能、灵活的配置、多种功能的组合是 zTree 最大优点。
zTree官网:http://www.treejs.cn/
项目地址:https://github.com/zTree/zTree_v3
zTree v3.5.28 API 文档:http://www.treejs.cn/v3/api.php
zTree Demo:http://www.treejs.cn/v3/demo.php
实践版本:zTree-verson : 3.5.28
1.首先引入:插件css和js文件
<link rel="stylesheet" href="static/dist/css/zTreeStyle.css">
<script src='static/dist/js/jquery.ztree.all-3.5.min.js'></script>
//js引入可以根据需要引入局部模块
2.页面html节点
<ul id="treeDemo" class="ztree"></ul>
//zTree 的容器样式名固定设置为: "ztree"
3.ztree初始化
var zTreeObj;
// zTree 的参数配置,深入使用请参考 API 文档(setting 配置详解)
var setting = {};
// zTree 的数据属性,深入使用请参考 API 文档(zTreeNode 节点数据详解)
var zNodes = [
{name:"test1", open:true, children:[
{name:"test1_1"}, {name:"test1_2"}]},
{name:"test2", open:true, children:[
{name:"test2_1"}, {name:"test2_2"}]}
];
$(document).ready(function(){
zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
});
实践示例:
自定义不同层级显示不同操作按钮,皮肤样式自定义,操作更新数据,保持折叠展开状态。
思路:
1. 自定义控件利用zTree初始化配置的view的addDiyDom方法js拼接Dom结构,Dom结构css自定义写成自己的样式。
2. 操作数据更新视图,由于实践示例的数据结构是经过加工处理的,采用的是zTree更新整个树的方法:treeObj.reAsyncChildNodes(null, "refresh");
3. 记录展开折叠状态,借助cookie记录,引入jquery.cookie.js,通过记录zTree节点id的状态方法来处理展开折叠状态:treeObj.getNodeByParam('id', z_tree[i])
4.展开折叠视图方法:treeObj.expandNode(node, true); 折叠展开回调事件:onExpand,onCollapse
html:
<div class="zTreeDemoBackground left">
<ul id="organizationTree" class="ztree"></ul>
</div>
js(代码框架为avalonjs):
//新增节点
addNodesFun:function(){
var orgIdVal;
var orgNameVal;
if(organizationStructure.communityOrgLevel == 99){
if(organizationStructure.addPropertyCompany.communityId == ''){
util.showTip('请选择小区');
return;
}
orgIdVal = organizationStructure.addPropertyCompany.communityId;
orgNameVal = $(".selectbox2 option:selected").text();
}else{
if(organizationStructure.addPropertyCompany.propertyCompanyId == ''){
var strTxt = $('#addModal1 .j-modalLabel').text();
if(strTxt.indexOf("物业公司")>=0){
util.showTip('请选择物业公司');
return;
}
if(strTxt.indexOf("分公司")>=0){
util.showTip('请选择分公司');
return;
}
}
orgIdVal = organizationStructure.addPropertyCompany.propertyCompanyId;
orgNameVal = $(".selectbox1 option:selected").text();
}
$.post("/imapi/sys/auth/addAuthNode", {
login: main.userObject.login,
orgId: orgIdVal,
orgName: orgNameVal,
orgLevel: organizationStructure.communityOrgLevel,
sort: organizationStructure.addPropertyCompany.PropertyCompanySort,
parentId: organizationStructure.nodeSysOrgAuthId
}, function (data) {
if (data.code || data.code == 0) {
util.showTip(data.message);
return;
}
$('.modal').modal('hide');
organizationStructure.getOrgList();
organizationStructure.updataTree();
util.showTip('操作成功');
}).error(function (xhr, status, statusText) {
util.removeLoading();
util.showTip('错误状态码:' + xhr.status + "<br>时间:" + xhr.getResponseHeader('Date'))
})
},
//删除节点
delNodesFun: function(sysOrgAuthId) {
organizationStructure.remindFunc('提示','确定删除嘛?',function(){ //remindfunc为自定义询问提示方法,非ztree的方法
$.post("/imapi/sys/auth/delAuthNode", {
login: main.userObject.login,
sysOrgAuthId: sysOrgAuthId
}, function (data) {
if (data.code || data.code == 0) {
util.showTip(data.message);
return;
}
organizationStructure.getOrgList();
organizationStructure.updataTree();
util.showTip("删除成功!");
}).error(function (xhr, status, statusText) {
util.removeLoading();
util.showTip('错误状态码:' + xhr.status + "<br>时间:" + xhr.getResponseHeader('Date'));
})
})
},
//更新树
updataTree:function(){
var treeObj = $.fn.zTree.getZTreeObj("organizationTree");
treeObj.reAsyncChildNodes(null, "refresh");
},
//节点树数据构造
initTreeNode:function(data){
var nodeList=[];
for(var i=0;i<data.length;++i){
nodeList[i]={};
nodeList[i].id=data[i].orgId;
nodeList[i].name=data[i].orgName;
nodeList[i].sysOrgAuthId=data[i].sysOrgAuthId;
nodeList[i].orgLevel=data[i].orgLevel;
if(data[i].leafList&&data[i].leafList.length>0){
nodeList[i].children = arguments.callee(data[i].leafList);
}
}
return nodeList;
},
//初始化节点树
initTree: function(nodeData,id){
var zNodes = [];
zNodes = nodeData;
var setting_organization = {
view: {
showIcon:false,
addDiyDom: organizationStructure.addDiyDom //注:这里是传的函数名
},
callback: {
onExpand: organizationStructure.onExpand,
onCollapse: organizationStructure.onCollapse
}
};
$(document).ready(function(){
if('organizationTree' == id){
$.fn.zTree.init($("#"+id), setting_organization, zNodes);
var treeObj = $.fn.zTree.getZTreeObj("organizationTree");
//treeObj.expandAll(true); //控制展开折叠
var cookie = $.cookie("z_tree");
if(cookie){ z_tree = JSON.parse(cookie);
for(var i=0; i< z_tree.length; i++){
var node = treeObj.getNodeByParam('id', z_tree[i])
treeObj.expandNode(node, true) }
}
}
});
},
//展开折叠状态
onExpand: function(event, treeId, treeNode){
var cookie = $.cookie("z_tree");
var z_tree = null;
if(cookie){
z_tree = JSON.parse(cookie);
}
if(!z_tree){ z_tree = new Array(); }
if(jQuery.inArray(treeNode.id, z_tree)<0){
z_tree.push(treeNode.id); }
$.cookie("z_tree", JSON.stringify(z_tree))
},
onCollapse: function(event, treeId, treeNode){
var cookie = $.cookie("z_tree");
var z_tree = null;
if(cookie){
z_tree = JSON.parse(cookie);
}
if(!z_tree){
z_tree = new Array();
}
var index = jQuery.inArray(treeNode.id, z_tree);
z_tree.splice(index, 1);
$.cookie("z_tree", JSON.stringify(z_tree))
},
//自定义节点树控件
addDiyDom:function(treeId, treeNode) {
//if (treeNode.parentNode && treeNode.parentNode.id!=2) return;
var aObj = $("#" + treeNode.tId + '_a');
console.log(treeId);
console.log(treeNode);
if (treeNode.level == 0) {
var editStr = "<a id='diyBtn1_" +treeNode.id+ "' data-sysOrgAuthId='"+treeNode.sysOrgAuthId+ "' class='company-op addcompany-p'>新增物业公司</a>";
aObj.after(editStr);
} else if(treeNode.orgLevel == 99){
var editStr = "<a id='diyBtn1_" +treeNode.id+ "' data-sysOrgAuthId='"+treeNode.sysOrgAuthId+ "' class='company-op deletecompany'>删除</a>";
aObj.after(editStr);
}else{
var editStr = "<a id='diyBtn1_" +treeNode.id+ "' data-sysOrgAuthId='"+treeNode.sysOrgAuthId+ "' class='company-op deletecompany'>删除</a>" + "<a id='diyBtn1_" +treeNode.id+ "' data-sysOrgAuthId='"+treeNode.sysOrgAuthId+ "' class='company-op addcompany-s'>新增分公司</a>" + "<a id='diyBtn2_" +treeNode.id+ "' data-sysOrgAuthId='"+treeNode.sysOrgAuthId+ "' class='company-op addcompany-c'>新增小区</a>";
aObj.after(editStr);
}
$(document).on('click','.addcompany-p',function(){
organizationStructure.addNodeshow = true;
organizationStructure.addPropertyCompany.propertyCompanyId = '';
organizationStructure.addPropertyCompany.communityId = '';
organizationStructure.addPropertyCompany.PropertyCompanySort = '';
organizationStructure.nodeSysOrgAuthId = $(this).attr('data-sysOrgAuthId');
organizationStructure.communityOrgLevel = '';
$('#addModal1').find('.j-modalLabel').text('新增物业公司');
$('#addModal1').modal('show');
});
$(document).on('click','.addcompany-s',function(){
organizationStructure.addNodeshow = true;
organizationStructure.addPropertyCompany.propertyCompanyId = '';
organizationStructure.addPropertyCompany.communityId = '';
organizationStructure.addPropertyCompany.PropertyCompanySort = '';
organizationStructure.nodeSysOrgAuthId = $(this).attr('data-sysOrgAuthId');
organizationStructure.communityOrgLevel = '';
$('#addModal1').find('.j-modalLabel').text('新增分公司');
$('#addModal1').modal('show');
});
$(document).on('click','.addcompany-c',function(){
organizationStructure.addNodeshow = false;
organizationStructure.addPropertyCompany.propertyCompanyId = '';
organizationStructure.addPropertyCompany.communityId = '';
organizationStructure.addPropertyCompany.PropertyCompanySort = '';
organizationStructure.nodeSysOrgAuthId = $(this).attr('data-sysOrgAuthId');
organizationStructure.communityOrgLevel = 99;
$('#addModal1').find('.j-modalLabel').text('新增小区');
$('#addModal1').modal('show');
});
$(document).on('click','.deletecompany',function(){
var curSysOrgAuthId = $(this).attr('data-sysOrgAuthId');
organizationStructure.delNodesFun(curSysOrgAuthId);
});
},
//获取节点树列表
getOrgList:function(){
$.post('/imapi/sys/auth/authTree', {login:main.userObject.login,containRootNode:true},
function (data) {
if(data.code||data.code == 0){
util.showTip(data.message);
return;
}
var nodeData = organizationStructure.initTreeNode(data);
organizationStructure.initTree(nodeData,"organizationTree");
//ztree checkbox 禁用编辑
var zTreeObj = $.fn.zTree.getZTreeObj("organizationTree");
var nodes = zTreeObj.getNodes(), disabled = true, inheritParent = true, inheritChildren = true;
for (var i = 0, l = nodes.length; i < l; i++) {
zTreeObj.setChkDisabled(nodes[i], disabled, inheritParent, inheritChildren);
}
}).error(function(xhr,status,statusText){
util.showTip('错误状态码:'+xhr.status+"<br>时间:"+xhr.getResponseHeader('Date'))
})
}
3.ztree树json数据结构:
[
{
"sysOrgAuthId":"主键",
"orgId":"组织id(物业公司、分公司、小区id)",
"orgName":"组织名称(物业公司、分公司、小区名称)"
"parentId":"父级结点id",
"leafList":[
{
"sysOrgAuthId":"主键",
"orgId":"组织id(物业公司、分公司、小区id)",
"parentId":"父级结点id",
"orgName":"组织名称(物业公司、分公司、小区名称)",
"leafList":[]
}]
},
{}
]