日期:2014-05-16  浏览次数:20283 次

使用jsTree按需装载子节点

本文主要内容:

一、jsTree的基本使用方法;

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

?

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

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

?

一、jsTree的基本使用方法:

?

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

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

?

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

<div id="myTree"></div>

?

3. 生成树的js方法:

$("#myTree").tree({
	data : { 
		type : "json",
		url : "getChildren.do"
	}
});

这是最简单的写法,更多配置可参考documentation.html里的Configuration段。

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

{ 
	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配置项如下:

$("#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是其在数组中的索引。

1 楼 ihibernate 2010-06-11  
,楼主真的很强大!
那么在多级tre的情况下,该怎么创建子级树呢?
 tree_obj.create(entry, node, entryIndex + 1); 

此处代码中我又该如何替换呢?
2 楼 ihibernate 2010-06-11  
ihibernate 写道
,楼主真的很强大!
那么在多级 Tree 的情况下,该怎么创建子级树呢?
 tree_obj.create(entry, node, entryIndex + 1); 

此处代码中我又该如何替换呢?