`
ganjuelovejava
  • 浏览: 92093 次
  • 性别: Icon_minigender_2
  • 来自: 湖南
社区版块
存档分类
最新评论
阅读更多
使用jsTree按需装载子节点
文章分类:Web前端
本文主要内容:

一、jsTree的基本使用方法;

二、按需装载子节点,即每次展开某节点时,才去服务器装载其子节点。



jsTree是基于jQuery的一个树形插件,该项目主页:http://www.jstree.com/

本文使用版本为0.9.9a,主要参考文档在下载包里的documentation.html文件。



一、jsTree的基本使用方法:



1. 在页面导入必要的库文件:

基本的使用只需要jquery.js和jquery.tree.js两个文件,都在jsTree的下载包里,不同版本的jsTree需要导入的库文件可能不同。



2. 在页面需要显示树的地方:

Html代码
1.<div id="myTree"></div> 
<div id="myTree"></div>

3. 生成树的js方法:

Js代码
1.$("#myTree").tree({  
2.    data : {   
3.        type : "json",  
4.        url : "getChildren.do" 
5.    }  
6.}); 
$("#myTree").tree({
data : {
type : "json",
url : "getChildren.do"
}
});这是最简单的写法,更多配置可参考documentation.html里的Configuration段。

其中type指返回的数据类型,这里设置为json,所以url请求返回的数据必需是jsTree约定的json格式,对于每个节点最基本的格式如下:

Js代码
1.{   
2.    attributes: { id : "node_identificator", some-other-attribute : "attribute_value" },   
3.    data: "node_title",   
4.    // Properties below are only used for NON-leaf nodes  
5.    state: "closed", // or "open"  
6.    children: [ /* an array of child nodes objects */ ]  
7.} 
{
attributes: { id : "node_identificator", some-other-attribute : "attribute_value" },
data: "node_title",
// Properties below are only used for NON-leaf nodes
state: "closed", // or "open"
children: [ /* an array of child nodes objects */ ]
}
attributes里为自定义属性,data为节点显示的文本,state值为closed时,节点前面有表示节点可以被展开的标识。还有其它写法可参考documentation.html里的Datastores段。



二、按需装载子节点:

在上面基本使用方法的第3点里提到更多配置可参考documentation.html里的Configuration段,其中有一个callback配置项,按需装载子节点可以通过这里的onopen事件触发,即当展开节点时。在上面第3点的代码里加上callback配置项如下:

Js代码
1.$("#myTree").tree({  
2.    data : {   
3.        type : "json",  
4.        async : true,  
5.        url : "getChildren.do" 
6.    },  
7.    callback : {  
8.        onopen : function (node, tree_obj) {  
9.            if (tree_obj.children(node).length == 0) {  
10.                $.getJSON('getChildren.do, {'id' : node.id}, function(data) {  
11.                    $.each(data, function(entryIndex, entry) {  
12.                        tree_obj.create(entry, node, entryIndex + 1);  
13.                    });  
14.                });  
15.            }  
16.            return true;  
17.        }  
18.    }  
19.}); 
$("#myTree").tree({
data : {
type : "json",
async : true,
url : "getChildren.do"
},
callback : {
onopen : function (node, tree_obj) {
if (tree_obj.children(node).length == 0) {
$.getJSON('getChildren.do, {'id' : node.id}, function(data) {
$.each(data, function(entryIndex, entry) {
tree_obj.create(entry, node, entryIndex + 1);
});
});
}
return true;
}
}
});其中, $.getJSON和$.each方法是jQuery中的方法,children和create是jsTree的方法,在documentation.html里的API段里可找到它们的使用说明。上面代码中依次出现的参数,node是要展开的节点对象,tree_obj是整个树对象,data是请求返回的json格式数据,依然是要符合之前提到的约定格式。entry是遍历返回的节点数组时的当前节点,entryIndex是其在数组中的索引。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics