<!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: ""
}
},
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');
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>