jstree使用心得

最近使用到了jstree(v3.3.4)这个插件(官网:https://www.jstree.com/),在这里记录下我的使用过程的一些技巧和问题。

1、 获取数据

一般实际项目中用到的数据都是ajax请求后台的,所以格式参考的是jstree的API中的$.jstree.defaults.core.data。因为使用的ajax是封装好的,所以参考function的格式。

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

2、data格式

为了方便,获取到的数据整合为

{ "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 } //选中和展开

3、types

"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" : []
    }
  }

4、get_selected([full])

获取当前jstree选中的节点属性,若full为true,只返回id,否则返回所有属性(包括父节点、所有父节点、属于树的第几级等)。在使用search时很好用:

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

5、插件plugins

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

"plugins" : [
    "checkbox", //添加checkbox
    "contextmenu", //选中右键文本内容
    "dnd", //是否可以拖拽
    "massload",
    "search", //搜索
    "sort", //排序
    "state", //在刷新之后保持刷新之前状态(比如选中和展开)
    "types", //设置types
    "unique", 
    "wholerow", //选中整行
    "changed",
    "conditionalselect"
]

6、其他

还有一些其他事件,比如:

$("#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){}

其他没用上的等以后用上了再补充。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值