zTree学习笔记二:展开树和收起树

时间:2021-11-15 12:36:12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="../css/zTreeStyle/zTreeStyle.css">
<script src="../js/jquery-1.4.4.min.js"></script>
<script src="../js/jquery.ztree.all.min.js"></script>
</head>
<body>
<ul id="leftTree" class="ztree"></ul>
<button onclick="expandTree()">展开</button>
<button onclick="closeTree()">合并</button>
<script>
var setting = {
check:{
enable:true //显示勾选框
},
view: {
showIcon: false,//是否显示节点的图标
showLine: true,//显示节点之间的连线。
expandSpeed: "slow",//节点展开、折叠时的动画速度
selectedMulti: false//不允许同时选中多个节点。
},
data: {
simpleData: {
enable:true, //使用简单数据模式
idKey: "id",//节点数据中保存唯一标识的属性名称
pIdKey: "pId",//节点数据中保存其父节点唯一标识的属性名称
rootPId: "" //用于修正根节点父节点数据 默认值:null
}
},
callback: {}
};
var nodes = [
{id :"1",pId:"0",name :"山西省"},
{id :"2",pId:"0",name : "河北省"},
{id :"3",pId:"0",name : "内蒙省"},
{id :"4",pId:"0",name : "吉林省"},
{id :"11",pId:"1",name: "大同市"},
{id :"12",pId:"1",name: "朔州市"},
{id :"21",pId:"2",name: "石家庄"},
{id :"22",pId:"2",name: "唐山市"},
{id :"31",pId:"3",name: "赤峰市"},
{id :"32",pId:"3",name: "呼市"},
{id :"41",pId:"4",name: "长春市"},
{id :"42",pId:"4",name: "四平市"},
{id :"43",pId:"4",name: "辽源市"},
{id :"111",pId:"11",name:"浑源县"},
{id :"112",pId:"11",name: "阳高县"},
{id :"121",pId:"12",name: "山阴县"},
{id :"122",pId:"12",name: "应县"}
];
var tree = $.fn.zTree.init($('#leftTree'), setting, nodes);
tree.expandAll(tree);//默认是展开的
//展开树
function expandTree() {
var tree = $.fn.zTree.getZTreeObj('leftTree');
tree.expandAll(tree);
}
//收起树:只展开根节点下的一级节点
function closeTree() {
var tree = $.fn.zTree.getZTreeObj('leftTree');
//获取 zTree 的全部节点数据将节点数据转换为简单 Array 格式
var nodes = tree.transformToArray(tree.getNodes());
for(var i=0;i<nodes.length;i++){
if(nodes[i].level == 0){
console.log(nodes[i].name);
//根节点展开
tree.expandNode(nodes[i],true,true,false)
}else{
tree.expandNode(nodes[i],false,true,false)
}
}
}
</script>
</body>
</html>