最近使用到了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){}
其余没用上的等之后用上了再补充。