DIV CSS 佈局教程網

jstree 入門實例:樹狀選單的建立與互動
編輯:關於JavaScript     

jstree 是一款相當靈活、可高度客製化的樹狀選單外掛,很適合用來呈現層級式的分類資料。本文以一個「案由列表」的實際案例,記錄 jstree 的建立、節點事件、展開收縮控制,以及內建搜尋外掛的使用方式。

官方 API 與 demo 可參考:https://www.jstree.com/api/#/ 以及 GitHub 專案 https://github.com/vakata/jstree

HTML 程式碼

 <!-- 搜索框 --> <div class="search_input"> <input type="text" id="search_ay" /> <img src="/sfytj/dist/images/icon/ss_search.png" /> </div> <!-- 案由列表 --> <div class="reason_list"> <div id="treeview1" class="treeview"> </div> </div> 

JS 程式碼

1)建立 jstree:

 $("#treeview1").jstree({ 'core' : { "multiple" : false, 'data' : ay_mssys, 'dblclick_toggle': false //禁用tree的雙擊展開 }, "plugins" : ["search"] }); var ay_mssys = [ { "id": "1", "text": "民事案由(2008版)", "state": { "opened": true, //展示第一個層級下面的node "disabled": true //該根節點不可點擊 }, "children": [ { "id": "2", "text": "人格權糾紛", "children": [ { "id": "3", "text": "人格權糾紛", "children": [ { "id": "4", "text": "生命權、健康權、身體權糾紛", "children": [ { "id": "5", "text": "道路交通事故人身損害賠償糾紛" } ] } ] } ] } ] } ] //core:整個jstree顯示的核心,裡面包括多種項配置: //data: 這裡是使用json格式的數據;還可以使用html或者ajax請求等 //plugins: 這個jstree引用了哪些插件 //multiple : false 不可多選 

其中 core 是整棵樹顯示的核心,data 支援 json、html 或 ajax 等多種資料來源,plugins 決定引用哪些外掛,multiple 設為 false 表示不可多選。

2)點擊節點時取得該節點的 text、id 等資訊:

 //tree change時事件 $('#treeview1').on("changed.jstree", function (e, data) { console.log("The selected nodes are:"); console.log(data.node.id); //選擇的node id console.log(data.node.text); //選擇的node text form_data.ay = data.node.text; form_data.ay_id = data.node.id; }); //changed.jstree,jstree改變時發生的事件,類似的還有select_node.jstree等,api中有。 

3)點擊節點時控制展開、收縮:

 //jstree單擊事件 $("#treeview1").bind("select_node.jstree", function (e, data) { if(data.node.id !=1 ){ //排除第一個節點(2011民事案由) data.instance.toggle_node(data.node); //單擊展開下面的節點 } }); 

4)使用內建 search 外掛做搜尋:

 //輸入框輸入定時自動搜索 var to = false; $('#search_ay').keyup(function () { if(to) { clearTimeout(to); } to = setTimeout(function () { $('#treeview1').jstree(true).search($('#search_ay').val()); }, 250); }); 

這裡用 debounce 手法,讓使用者停止打字 250 毫秒後才觸發搜尋,避免每次按鍵都重新過濾造成效能浪費。透過 changed.jstree、select_node.jstree 等事件,就能靈活地把 jstree 整合進表單或權限設定的流程中。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved