前端-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){}

posted @ 2018-04-10 17:01  tuanz  阅读(609)  评论(0编辑  收藏  举报