首先這兩個文件是必須要引用的,還有就是引用 jQuery 文件就不說了:
<link href="/css/plugins/jsTree/style.min.css" rel="stylesheet" />
<script src="/js/plugins/jsTree/jstree.min.js"></script>
//這個是關鍵,如果不清空實例,jstree不會重新生成 $('#jstree1').data('jstree', false).empty(); $('#jstree1').jstree({ 'core': { 'data': { 'url': '/API/ajax_nodes.ashx', //異步加載jstree html格式的數據地址 'data': function (node) { return { 'id': node.id }; } } } }).bind('select_node.jstree', function (event, data) { //綁定的點擊事件 menuid = data.node.data.menuid + ""; // 獲取我自己定義的屬性menuid,可以根據自己實際情況定義 }); //隱藏圖標,因為覺得太難看了,我沒有使用jstree 樣式的插件 “plugs” ,因為異步刷新數據之后就沒有效果了,果斷放棄 $('#jstree1').jstree().hide_icons();
//還可以根據需要綁定點擊事件 //.bind('click.jstree', function (event, data) { // alert($(event.target).parents('li').attr('data-menuid')); //});
后台獲取到的代碼格式如下
<ul> <li data-menuid='3e544d7a-d850-4785-9648-feafc4698a3b'>系統管理<ul> <li data-menuid='545d2450-4dac-4377-afbe-d9aa451f795f' data-jstree='{"type":"html"}'>角色管理 <ul> <li data-menuid='810a72f0-55d3-468f-8653-10d1b06a4234' data-jstree='{"type":"html"}'>角色 - 分配權限頁 <ul></ul> </li> <li data-menuid='02b48102-4e8a-44fb-84a0-7a8c8535676a' data-jstree='{"type":"html"}'>角色 - 詳細信息頁 <ul></ul> </li> </ul> </li> <li data-menuid='e620450b-6d17-4192-bee0-66fbd114e82a' data-jstree='{"type":"html"}'>部門管理123211 <ul></ul> </li> </ul> </li> </ul>
jsTree還提供幾個api來設置主題的行為
.set_theme(name, url):設置主題
.get_theme():取得當前激活即使用的主題
.show_dots(),.hide_dots(),.toggle_dots():顯示、隱藏、激活樹邊框的點
.show_icons(),.hide_icons(),.toggle_icons():顯示、隱藏、激活樹的圖標
在項目中使用的時候,就可以直接把以上代碼封裝成一個方法,加載和刷新數據的時候可以直接調用就行。