前端控件之树型结构dTree.js使用

J2EE 专栏收录该内容
7 篇文章 0 订阅

dTree.js和dTree.css下载地址:http://www.destroydrop.com/javascripts/tree/


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

  • 先看一眼dtree给的例子

  • 构造静态树

首先引入css文件和js文件

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

  构造静态树其实很简单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<div class = "cnblogs_Highlighter" ><pre class = "brush:javascript" ><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>
</pre>
</div>

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

 

  • API文档
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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.

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

  •  初始化数据库并加入数据
1
2
3
4
5
6
7
8
9
10
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是父子的关系。

1
insert  into `tree_table`(`id`,`nodeId`,`parentId`,`hrefAddress`,`nodeName`) values (1, '1' , '-1' , 'http://www.sohu.com' , '北京' );
1
<pre class = "brush:javascript" >insert  into `tree_table`(`id`,`nodeId`,`parentId`,`hrefAddress`,`nodeName`) values (1, '1' , '-1' , 'http://www.sohu.com' , '海淀区' );</pre>
  • 创建数据读取类和方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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类

1
2
3
4
5
6
7
private  int  id;
     private  String nodeId;
     private  String parentId;
     private  String hrefAddress;
     private  String nodeName;
 
....set/get
  • 构造页面并且显示树型结构

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version= "1.0"  encoding= "UTF-8" ?>
<web-app version= "2.4"
     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方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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方法读取数据并且返回,然后显示到页面上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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 );