前言:最近写了个小demo,使用 jstree 来加载一棵树,网上也能搜到一部分资料,但是大都讲的不太明白,本文展示了一个简单但完整的示例。
整个过程可以分为四步:
0.前期准备
主要是引入一下jstree的css和js,以及jquery。
1.数据准备
2.初始化树
3.加载事件
废话不多说,直接上代码:
JavaScript Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
//数组准备
var arr = [ { id: "root1" , text: "根节点1" , parent: "#" , state: { opened: true , selected: true , } }, { id: "root1_sub1" , text: "子节点1" , parent: "root1" , state: { opened: true , selected: true , } }, { id: "root1_sub2" , text: "子节点2" , parent: "root1" , state: { opened: true , selected: true , } }, { id: "root2" , text: "根节点2" , parent: "#" , state: { opened: true , selected: true , } }, { id: "root2_sub1" , text: "子节点1" , parent: "root2" , state: { opened: true , selected: true , } }, { id: "root2_sub2" , text: "子节点2" , parent: "root2" , state: { opened: true , selected: true , } } ]; //初始化树 $( function () { $( "#treebox" ).jstree( { core: { data: arr, check_callback: true , //是否允许动态增加删除节点 expand_selected_onload: true , //加载完成后是否展开所有选中的节点 themes: { dots: true , //是否显示连接线 icons: true , //是否显示图标 } }, plugins: [ "checkbox" ], checkbox: { keep_selected_style: true , //是否默认选中 three_state: true , //是否父子级别级联 tie_selection: true , //复选框是否与树的选择绑定 whole_node: true //复选框是否与节点关联 } } ); } ); var allLayers = []; map.layers.forEach( function (item) { allLayers.push(item.id); } ); //绑定事件 $( "#treebox" ).on( "changed.jstree" , function (event, data) { console.log(data); //获取所有选中的节点,这些节点对应的图层要显示 var needShowLayer = $( "#treebox" ).jstree().get_checked(); needShowLayer.forEach( function (item) { //TODO:展示 } ); //找到所有要隐藏的图层 allLayers.forEach( function (item) { if (needShowLayer.indexOf(item) == - 1 ) { //TODO:隐藏 } } ); } ); |
结语:如果复选框不能出现,要看console里面有没有资源的报错说明,jstree的资源文件主要是两个,一个是雪碧图32px.png和一个loading的gif图标throbber.gif,所以这里面的复选框不是真正的复选框,而是一个图片。
最后,我们来看下32px.png长啥样: