1:点击全选可选中或取消选中全部节点,全部展开可展开或折叠所有节点
2:单个节点的选中或折叠等操作会影响全选和展开按钮状态
源码:
setting = {
...
callback: {
onCheck: zTreeOnCheck,
onExpand: zTreeOnExpand,
onCollapse: zTreeOnCollapse
}
...
}
$.fn.zTree.init($("#tree"), setting, treeNodes);
var open = fold = true;
function zTreeOnExpand(event, treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj("tree");
var nodes = zTree.getNodes();
//所有节点都是展开状态
open = isOpen(nodes,0);
//有节点折叠
if(open){
$('#fold span').text('全部折叠');
$('#fold img').attr('src','../../../image/fold.png');
fold = true
}
}
function zTreeOnCollapse(event, treeId, treeNode) {
//所有节点都是折叠状态
var zTree = $.fn.zTree.getZTreeObj("tree");
var nodes = zTree.getNodes();
var val = isOpen(nodes,1);
//有节点折叠
if(!val){
$('#fold span').text('全部展开');
$('#fold img').attr('src','../../../image/open.png');
fold = false
}
open = true;
}
function isOpen (nodes, type){
for (var i = 0; i < nodes.length; i++){
if(type){//折叠操作
//只要有一个节点为折叠状态,返回false
if(open){
if(nodes[i].children != undefined){
open = nodes[i].open;
if(!open){
return open
}else{
isOpen(nodes[i].children)//遍历直节点
}
}
}else{
return open
}
}else{
if(open){
return open
}else{
if(nodes[i].children != undefined){
open = nodes[i].open;
if(open){
return open
}else{
isOpen(nodes[i].children)
}
}
}
}
}
}
function zTreeOnCheck(event, treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj("tree");
var node = zTree.getNodes();
var nodes = zTree.transformToArray(node).length;
var checkNode = zTree.getCheckedNodes().length;
if(nodes == checkNode){
$('#all').prop('checked', true)
}else{
$('#all').prop('checked', false)
}
}
$('#all').on('click',function (e) {
var zTree = $.fn.zTree.getZTreeObj("tree");
var node = zTree.getNodes();
var nodes = zTree.transformToArray(node);
var checkNode = zTree.getCheckedNodes().length;
//已选中的节点数小于总数 - 全选
if (checkNode < nodes.length) {
$('#all').prop('checked', true)
zTree.checkAllNodes(true);
} else{
zTree.checkAllNodes(false);
}
})
$('#fold').on('click',function (e) {
var zTree = $.fn.zTree.getZTreeObj("tree");
if (fold) {
$('#fold span').text('全部展开');
$('#fold img').attr('src','../../../image/open.png');
zTree.expandAll(false);
fold = false
} else{
$('#fold span').text('全部折叠');
$('#fold img').attr('src','../../../image/fold.png');
zTree.expandAll(true);
fold = true
}
})