dtree和jquery构建树型结构


对于小型的树型应用来说,dtree是一个不错的选择。

先看一眼dtree给的例子

构造静态树

首先引入css文件和js文件

<link rel="StyleSheet" href="dtree.css" type="text/css" />
	<script type="text/javascript" src="dtree.js"></script>

  构造静态树其实很简单

<script>
		       /*   
			 		tree.add(id,pid,name,url,title,target,icon,iconOpen,open);
				    id        :节点自身的id
					pid       :节点的父节点的id
					name      :节点显示在页面上的名称
					url       :节点的链接地址
					title     :鼠标放在节点上所出现的提示信息
					target    :节点链接所打开的目标frame(如框架目标mainFrame或是_blank,_self之类)
					icon      :节点关闭时的显示图片的路径
					iconOpen  :节点打开时的显示图片的路径
					open      :布尔型,节点是否打开(默认为false)
				    ------------------------------------------------
				    东城区、西城区、崇文区、宣武区、朝阳区、丰台区、石景山区、
				    海淀区、门头沟区、房山区、通州区、顺义区、 昌平区、
				   大兴区、怀柔区、平谷区 、 密云县、延庆县
				   ------------------------------------------------
				*/
		</script>
				<script type="text/javascript">
				 tree = new dTree('tree');//创建一个对象.
				 tree.add("1","-1","中国","","","","","",false);
				 tree.add("11","1","北京","","","","","",false);
				 tree.add("110","11","东城区","连接地址可以从数据库里面动态查询出来..","东城区","打开目标位置");
				 tree.add("111","11","西城区","连接地址可以从数据库里面动态查询出来..","","链接在哪里显示");
				 tree.add("112","11","崇文区","连接地址可以从数据库里面动态查询出来..","","mainFrame");
				 tree.add("113","11","宣武区","","","_blank");
				 tree.add("114","11","朝阳区","/.jsp","","mainFrame");
				 tree.add("115","11","丰台区","/.jsp","","mainFrame");
				 tree.add("116","11","石景山区","/.jsp","","mainFrame");
				 tree.add("117","11","海淀区","/.jsp","","mainFrame");
				 tree.add("118","11","门头沟区","/.jsp","","mainFrame");
				 tree.add("119","11","房山区","/.jsp","","mainFrame");
				 tree.add("120","11","通州区","/.jsp","","mainFrame");
				 tree.add("121","11","顺义区","/.jsp","","mainFrame"); 
				 tree.add("122","11","昌平区","/.jsp","","mainFrame");
				 tree.add("123","11","大兴区","/.jsp","","mainFrame");
				 tree.add("124","11","怀柔区","/.jsp","","mainFrame");
				 tree.add("125","11","平谷区","/.jsp","","mainFrame");
				 tree.add("126","11","延庆县","/.jsp","","mainFrame");
				 tree.add("127","11","密云县","/.jsp","","mainFrame");
				 //==================================================
				 tree.add("12","1","湖南","","","","","",false);
				 tree.add("121","12","株洲","javascript:调用本页内的js函数","","mainFrame");
				 tree.add("122","12","长沙");
				//====================================================
				 tree.add("13","1","湖北","","","","","",false);
				 tree.add("131","13","武汉","javascript:void()","","mainFrame");
				 tree.add("132","13","宜昌","javascript:void()","","mainFrame");
				 tree.add("133","13","孝感","javascript:void()","","mainFrame");
				 //===================================================	 
				 tree.add("14","1","广东","","","","","",false);
				 tree.add("141","14","佛山","javascript:void()","","mainFrame");
				 document.write(tree);
			    </script>

ok,静态树完成了,看一眼效果吧!是不是跟上面的一样!

 

API文档
Functions
add()
Adds a node to the tree.
Can only be called before the tree is drawn.

id, pid and name are required.

Parameters
Name Type Description 
id Number Unique identity number. 
pid Number Number refering to the parent node. The value for the root node has to be -1. 
name String Text label for the node. 
url String Url for the node. 
title String Title for the node. 
target String Target for the node. 
icon String Image file to use as the icon. Uses default if not specified. 
iconOpen String Image file to use as the open icon. Uses default if not specified. 
open Boolean Is the node open. 


Example
mytree.add(1, 0, 'My node', 'node.html', 'node title', 'mainframe', 'img/musicfolder.gif');


openAll()
Opens all the nodes.
Can be called before and after the tree is drawn.

Example
mytree.openAll();


closeAll()
Closes all the nodes.
Can be called before and after the tree is drawn.

Example
mytree.closeAll();


openTo()
Opens the tree to a certain node and can also select the node.
Can only be called after the tree is drawn.

Parameters
Name Type Description 
id Number Identity number for the node. 
select Boolean Should the node be selected. 

Example
mytree.openTo(4, true);

Configuration
Variable Type Default Description 
target String true Target for all the nodes. 
folderLinks Boolean true Should folders be links. 
useSelection Boolean true Nodes can be selected(highlighted). 
useCookies Boolean true The tree uses cookies to rember it's state. 
useLines Boolean true Tree is drawn with lines. 
useIcons Boolean true Tree is drawn with icons. 
useStatusText Boolean false Displays node names in the statusbar instead of the url. 
closeSameLevel Boolean false Only one node within a parent can be expanded at the same time. openAll() and closeAll() functions do not work when this is enabled. 
inOrder Boolean false If parent nodes are always added before children, setting this to true speeds up the tree. 

就是这么简单,一棵静态树就完成了。好下面加上动态的效果。

 初始化数据库并加入数据
DROP TABLE IF EXISTS `tree_table`;

CREATE TABLE `tree_table` (
  `id` int(11) NOT NULL auto_increment,
  `nodeId` varchar(12) NOT NULL  ,
  `parentId` varchar(12) NOT NULL  ,
  `hrefAddress` varchar(85)  ,
  `nodeName` varchar(20)  ,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

加入一些测试数据,注意nodeId和parentId是父子的关系。

insert  into `tree_table`(`id`,`nodeId`,`parentId`,`hrefAddress`,`nodeName`) values (1,'1','-1','http://www.sohu.com','北京');
insert  into `tree_table`(`id`,`nodeId`,`parentId`,`hrefAddress`,`nodeName`) values (1,'1','-1','http://www.sohu.com','海淀区');
创建数据读取类和方法
Connection con = null;

	public Connection getConnection() {
		Connection conn = null;
		String url = "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=gbk";
		String user = "root";
		String password = "mytopicforever";
		try {
			if (conn == null) {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
				conn = DriverManager.getConnection(url, user, password);
			}
		} catch (Exception e) {
			System.out.println("连接失败");
			return null;
		} finally {
			url = null;
			user = null;
			password = null;
		}
		return conn;
	}

	public ArrayList<Nodes> getNodeInfo() {
		String sql = "select nodeId ,parentId ,hrefAddress ,nodeName from tree_table order by id ";
		PreparedStatement pre = null;
		Connection conn = null;
		conn = getConnection();
		ResultSet rs = null;
		ArrayList<Nodes> list = new ArrayList<Nodes>();
		try {
			pre = conn.prepareStatement(sql);
			rs =pre.executeQuery();
			while (rs.next()){
				Nodes node = new Nodes();
				node.setHrefAddress(rs.getString("hrefAddress"));
				node.setNodeId(rs.getString("nodeId"));
				node.setParentId(rs.getString("parentId"));
				node.setNodeName(rs.getString("nodeName"));
				list.add(node);
			}
			rs.close();
			pre.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			 pre = null;
			 conn = null;
			 rs = null;
		}
        return list;
	}

数据库可以根据情况自己任意选择,也可以用hibernate或者ibaties,因为只是演示,所以用哪个来做都无所谓。

构造nodes类

private int id;
	private String nodeId;
	private String parentId;
	private String hrefAddress;
	private String nodeName;

....set/get
构造页面并且显示树型结构

首先配置好servlet用于读取数据并返回

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <servlet-name>NodesPrint</servlet-name>
    <servlet-class>com.handler.NodesPrint</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>NodesPrint</servlet-name>
    <url-pattern>/NodesPrint</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

servlet方法

	private static final long serialVersionUID = 1L;
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
                 doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		   System.out.println("调用了.........");
           request.setCharacterEncoding("utf-8");
           response.setContentType("text/xml;charset=utf-8");
           PrintWriter out = response.getWriter();
           DaoTest test = new DaoTest();
    	   ArrayList<Nodes> list=  test.getNodeInfo();
    	    if(list!=null&&list.size()>0){
    	    	out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    	        out.println("<nodes>");
    	    	for(int i=0;i<list.size();i++){
    	    		Nodes node = list.get(i);
    	    		out.println("<node nodeId='"+node.getNodeId()+"' parentId='"+node.getParentId()+"' hrefAddress='"+node.getHrefAddress()+"'>"+node.getNodeName()+"</node>");
    	    	}
    	    	out.println("</nodes>");
    	    }
	}

接着就是构造页面了,在页面加载的时候利用jquery的ajax方法读取数据并且返回,然后显示到页面上

tree = new dTree('tree');//创建一个对象.
								$.ajax({ 
										url:'NodesPrint', 
										type:'post', //数据发送方式 
										dataType:'xml', //接受数据格式 
										error:function(json){
				   							     alert( "not lived!");
											  },
										async: false ,
										success: function(xml){
				 								    $(xml).find("node").each(function(){ 
														  var nodeId=$(this).attr("nodeId");  
					  									  var parentId=$(this).attr("parentId");  
														  var hrefAddress=$(this).attr("hrefAddress");  
														  var nodeName=$(this).text(); 
														  tree.add(nodeId,parentId,nodeName,hrefAddress,"","","","",false);
								                     });
								                }
								  });
				      document.write(tree);

好了,现在到页面上去看一下效果吧,一棵动态树就这样完成了,是不是很简单,如果在业务量或者说数据量很小的情况下,这种方式是比较不错的,但是如果是大数据量的情况下建议采用异步加载的方案,就是每点击一个结点,读取子结点的数据并且动态的返回。