jstree使用心得

最近使用到了jstree(v3.3.4)這個插件(官網:https://www.jstree.com/),在這裏記錄下個人使用過程的一些技巧和問題。node

一、 獲取數據ajax

通常實際項目中用到的數據都是ajax請求後臺的,因此格式參考的是jstree的API中的$.jstree.defaults.core.data。由於使用的ajax是封裝好的,因此參考function的格式。json

$('#tree').jstree({
    'core' : {
        'data' : function (obj, callback) {
            callback.call(this, ['Root 1', 'Root 2']);
        }
    }
});

二、data格式this

爲了方便,獲取到的數據整合爲.net

{ "id" : "ajson1", "parent" : "#", "text" : "Simple root node", "icon" : 0 , 'state' : { 'selected' : true, 'opened' : true }}, 
{ "id" : "ajson2", "parent" : "ajson1", "text" : "Root node 1" , "icon" : 1 },
{ "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" , "icon" : 2 },
{ "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" , "icon" : 2 },
{ "id" : "ajson5", "parent" : "ajson4", "text" : "Child 3" , "icon" : 3 }

加上icon是爲了方便對應types對應。同時根節點的parent的值須要爲"#"。
'state' : { 'selected' : true, 'opened' : true } //選中和展開插件

三、typescode

"types" : {
    "0" : {
      "max_children" : 1, //最多孩子樹
      "max_depth" : 4, //最大子節點深度
      "valid_children" : ["2"] //能夠擁有孩子樹的節點
    },
    "1" : {
      "icon" : "/static/3.3.4/assets/images/tree_icon.png", //icon的圖片位置
      "valid_children" : []
    },
    "2" : {
      "icon" : false, //不要icon
      "valid_children" : []
    },
    "3" : {
      "icon" : "glyphicon glyphicon-file", //icon的className
      "valid_children" : []
    }
  }

四、get_selected([full])blog

獲取當前jstree選中的節點屬性,若full爲true,只返回id,不然返回全部屬性(包括父節點、全部父節點、屬於樹的第幾級等)。在使用search時很好用:排序

$('#tree').jstree(true).search(value);  //搜索的內容

五、插件plugins事件

jstree自帶了一些插件,只要在plugins中添加便可。

"plugins" : [
    "checkbox", //添加checkbox
    "contextmenu", //選中右鍵文本內容
    "dnd", //是否能夠拖拽
    "massload",
    "search", //搜索
    "sort", //排序
    "state", //在刷新以後保持刷新以前狀態(好比選中和展開)
    "types", //設置types
    "unique", 
    "wholerow", //選中整行
    "changed",
    "conditionalselect"
]

六、其餘

還有一些其餘事件,好比:

$("#tree").jstree({...}).on('loaded.jstree', function(e, data){  
    var inst = data.instance;  
    var obj = inst.get_node(e.target.firstChild.firstChild.lastChild);  
      
    inst.select_node(obj);  
});

http://blog.csdn.net/you8626/...默認選中根節點,試了有效,不過我請求到的數據可以判斷出根節點,能夠直接寫state參數,因此沒用上。

$("#tree").on('ready.jstree', function(e, data){}

其餘沒用上的等之後用上了再補充。

相關文章
相關標籤/搜索