最近使用到了jstree,感覺是一款靈活的、可多項定制的tree插件;
我這邊使用過程記錄下;
參考的jstree api網站,以及demo介紹:
https://www.jstree.com/api/#/
jstree api github:
https://github.com/vakata/jstree#populating-the-tree-using-a-callback-function
使用中的例子介紹:
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 不可多選
2)點擊jstree的每個子項,獲取該節點的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子項,控制該節點展開、收縮等:
//jstree單擊事件
$("#treeview1").bind("select_node.jstree", function (e, data) {
if(data.node.id !=1 ){ //排除第一個節點(2011民事案由)
data.instance.toggle_node(data.node); //單擊展開下面的節點
}
});
4)使用插件search搜索(jstree自帶的插件):
//輸入框輸入定時自動搜索
var to = false;
$('#search_ay').keyup(function () {
if(to) {
clearTimeout(to);
}
to = setTimeout(function () {
$('#treeview1').jstree(true).search($('#search_ay').val());
}, 250);
});
以上就是本文的全部內容,希望對大家有所幫助,同時也希望多多支持!