1. 程式人生 > >zTree學習筆記二:展開樹和收起樹

zTree學習筆記二:展開樹和收起樹

<!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>