傳統網站使用jq-ztree比較多,作一些技術總結
ztree網站api:http://www.treejs.cn/v3/api.phpjavascript
//引入css,本身的css,ztree的css <link rel="stylesheet" href="../../../css/main.css" type="text/css"> <link rel="stylesheet" href="../../../css/zTreeStyle/zTreeStyle.css" type="text/css"> //引入jq, ztree.core.js, <script type="text/javascript" src="../../../js/jquery-1.4.4.min.js"></script> <script type="text/javascript" src="../../../js/jquery.ztree.core-3.5.js"></script> //若是勾選,引入ztree.excheck.js <script type="text/javascript" src="../../../js/jquery.ztree.excheck-3.5.js"></script> //若是編輯樹【拖拽,刪除,批量加載】,引入ztree.exedit.js。 <script type="text/javascript" src="../../../js/jquery.ztree.exedit-3.5.js"></script> <script> //編寫配置代碼 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"} ] } ]; //將數據加載到DOM中 $(document).ready(function(){ zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes); }); </script> //dom文本中引用 <div> //id存放樹的區域,class須要添加ztree纔會有效果 <ul id="treeDemo" class="ztree"> </ul> </div>
一、節點不顯示 checkbox / radio
//想要節點不顯示勾選框,給數據添加nocheck屬性,默認false顯示,true爲不顯示。 var zNodes = [ { name:"test1", open:true, nocheck:true //nocheck爲true時沒有勾選框 children:[ {name:"test1_1"}, {name:"test1_2"} ] } ];
二、樹展開
//給數據添加open,默認false不展開,true展開。 var zNodes = [ { name:"test1", open:true, //open爲true時展開 nocheck:true children:[ {name:"test1_1"}, {name:"test1_2"} ] } ]; //經過獲取節點添加展開屬性 var zTreeObj = $.fn.zTree.getZTreeObj("tree"); var sNodes = zTreeObj .getSelectedNodes(); if (sNodes.length > 0) { var isOpen = sNodes[0].open; }
三、多層樹,數據沒有子元素的分級,在同一層時須要進行數據處理
//同一層的數據 { "list": [{ "value": "01", "text": "大業務" }, { "value": "02", "text": "大金融" }, { "value": "0101", "text": "大業務分支1" }, { "value": "0201", "text": "大金融分支1" }, { "value": "0202", "text": "大金融分支2" }, { "value": "020101", "text": "大金融分支1子分支1" }, { "value": "020102", "text": "大金融分支1子分支2" }] } //須要轉換ztree須要的分級格式,須要id,name,pId //pId指向當前節點的父級 $.each(data_type, function(i, v) { var bean = {}; bean.id = v.value; bean.name = v.text; bean.pId = v.value.slice(0, v.value.length - 2); //pId須要分級 }) //處理後的數據 { "list": [{ "id ": "01", "text": "大業務", "pId": "0", }, { "id": "02", "text": "大金融", "pId": "0", }, { "id": "0101", "text": "大業務分支1", "pId": "01", }, { "id": "0201", "text": "大金融分支1", "pId": "02", }, { "id": "0202", "text": "大金融分支2", "pId": "02", }, { "id": "020101", "text": "大金融分支1子分支1", "pId": "0201", }, { "id": "020102", "text": "大金融分支1子分支2", "pId": "0201", }] }