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);

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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏岑玉海

hbase源码系列(九)StoreFile存储格式

从这一章开始要讲Region Server这块的了,但是在讲Region Server这块之前得讲一下StoreFile,否则后面的不好讲下去,这块是基础,Re...

41650
来自专栏技术小讲堂

ASP.NET AJAX(7)_Microsoft AJAX Library扩展客户端组件继承时需要注意的问题扩展类型如何修改已有类型

首先,延续上一讲的内容,谈一下客户端面向对象类型系统中事件的使用 在C#中定义的一种方式 public class WorkEventArgs:EventArg...

28060
来自专栏YG小书屋

MapReduce:N keys,N files

MapReduce中,不管是map阶段还是reduce阶段,二者的输入和输出都是key,value类型的值。现在有个需求是根据map阶段返回值key的个数,生成...

9140
来自专栏数据结构与算法

BZOJ1269: [AHOI2006]文本编辑器editor

Descriptio 这些日子,可可不和卡卡一起玩了,原来可可正废寝忘食的想做一个简单而高效的文本编辑器。你能帮助他吗? 为了明确任务目标,可可对“文本编辑器...

29870
来自专栏窗户

我博客上的围棋js程序

  版权申明:本文为博主窗户(Colin Cai)原创,欢迎转帖。如要转贴,必须注明原文网址   http://www.cnblogs.com/Colin-C...

53260
来自专栏Spark学习技巧

textFile构建RDD的分区及compute计算策略

1,textFile A),第一点,就是输入格式,key,value类型及并行度的意义。 def textFile( path: String, mi...

26670
来自专栏机器人网

中英文对照,瞬间理解西门子PLC指令

指令( 英文全称意思 ) :指令含义 1、LD ( Load 装载 ) :动合触点 2、LDN ( Load Not 不装载 ) : 动断触点 3、A ( A...

36270
来自专栏程序员宝库

徒手撸框架---实现 Aop

原文:犀利豆的博客(https://www.xilidou.com/2018/01/13/spring-aop/) 上一讲我们讲解了 Spring 的 IoC ...

313120
来自专栏技术博客

Entity Framework DataAnnotations

DataAnnotation 特性由.NET 3.5中引进,给.NET中的类提供了一种添加验证的方式。但是在EF中它又可以对映射关系进行控制,相比较Fluent...

10230
来自专栏小勇DW3

Mybatis使用动态代理实现拦截器功能

  拦截器顾名思义为拦截某个功能的一个武器,在众多框架中均有“拦截器”。这个Plugin有什么用呢?或者说拦截器有什么用呢?可以想想拦截器是怎么实现的。Plug...

54220

扫码关注云+社区

领取腾讯云代金券