最近使用到了jstree,感觉是一款灵活的、可多项定制的tree插件;
我这边使用过程记录下;
参考的jstree api网站,以及demo介绍:
jstree api github:
使用中的例子介绍:
html代码:
- <!-- 搜索框 -->
- <div class="search_input">
- <input type="text" id="search_ay" />
- <img src="/sfytj/dist/images/icon/ss_search.png" />
- </div>
- <!-- 案由列表 -->
- <div class="reason_list">
- <div id="treeview1" class="treeview">
- </div>
- </div>
js代码:
1)生成jstree:
- $("#treeview1").jstree({
- 'core' : {
- "multiple" : false,
- 'data' : ay_mssys,
- 'dblclick_toggle': false //禁用tree的双击展开
- },
- "plugins" : ["search"]
- });
- var ay_mssys =
- [
- {
- "id": "1",
- "text": "民事案由(2008版)",
- "state": {
- "opened": true, //展示第一个层级下面的node
- "disabled": true //该根节点不可点击
- },
- "children":
- [
- {
- "id": "2",
- "text": "人格权纠纷",
- "children":
- [
- {
- "id": "3",
- "text": "人格权纠纷",
- "children": [
- {
- "id": "4",
- "text": "生命权、健康权、身体权纠纷",
- "children":
- [
- {
- "id": "5",
- "text": "道路交通事故人身损害赔偿纠纷"
- }
- ]
- }
- ]
- }
- ]
- }
- ]
- }
- ]
- //core:整个jstree显示的核心,里面包括多种项配置:
- //data: 这里是使用json格式的数据;还可以使用html或者ajax请求等
- //plugins: 这个jstree引用了哪些插件
- //multiple : false 不可多选
2)点击jstree的每个子项,获取该节点的text、id等信息:
- //tree change时事件
- $('#treeview1').on("changed.jstree", function (e, data) {
- console.log("The selected nodes are:");
- console.log(data.node.id); //选择的node id
- console.log(data.node.text); //选择的node text
- form_data.ay = data.node.text;
- form_data.ay_id = data.node.id;
- });
- //changed.jstree,jstree改变时发生的事件,类似的还有select_node.jstree等,api中有。
3)点击jstree子项,控制该节点展开、收缩等:
- //jstree单击事件
- $("#treeview1").bind("select_node.jstree", function (e, data) {
- if(data.node.id !=1 ){ //排除第一个节点(2011民事案由)
- data.instance.toggle_node(data.node); //单击展开下面的节点
- }
- });
4)使用插件search搜索(jstree自带的插件):
- //输入框输入定时自动搜索
- var to = false;
- $('#search_ay').keyup(function () {
- if(to) {
- clearTimeout(to);
- }
- to = setTimeout(function () {
- $('#treeview1').jstree(true).search($('#search_ay').val());
- }, 250);
- });