开发者社区> skyme张> 正文
阿里云
为了无法计算的价值
打开APP
阿里云APP内打开

dtree和jquery构建树型结构

简介: 对于小型的树型应用来说,dtree是一个不错的选择。 先看一眼dtree给的例子 构造静态树 首先引入css文件和js文件   构造静态树其实很简单 /* tree.
+关注继续查看

对于小型的树型应用来说,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);

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

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
某东网页(动态)搭建(jquery)
网页编程实战三: 利用jquery实现京东网页(动态)搭建,
5 0
大量文件名记录的树形结构存储
十多年来,NAS中已经存在的目录和文件达到10亿之多,在设计和开发备份系统的过程中碰到了很多挑战,本文将分享大量文件名记录的树形结构存储实践。
1595 0
jQuery+CSS3动画相册特效
在线演示 本地下载
713 0
Jquery树型表格
效果图 第一次写简书好激动,就是想和大家分享下 O(∩_∩)O哈哈哈~ 干货来了~~~~~~~~~ 首先是对数据的处理 接口返回的没有结构的数据,只有数据关系 这里要把这些没有结构的数据,进行树型结构处理,你们自...
836 0
jQuery UI Datepicker中文显示
jqueryuifunction [javascript] view plaincopy jQuery UI Datepicker这个用于日期显示很方便而且提供了多种样式,可以从jQuery UI中选择喜欢的样式和jQuery UI组件随意下载js库,如果只是使用datepicker那么选择时之选UI Core和Widgets中的Datepicker,然后选择喜欢的主题,选择版本,下载即可。
1028 0
dTree无限级目录树和JQuery同步ajax请求
以前都是用JQuery对树的支持来实现目录树的,近来闲来无事就弄了下dTree,感觉其无限级目录还是挺好的,而且它的使用也比较方便,基本上就是先把要用的js文件即dtree.js和css文件dtree.
744 0
+关注
236
文章
0
问答
文章排行榜
最热
最新
相关电子书
更多
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
冬季实战营第三期:MySQL数据库进阶实战
立即下载