javascript和jquery分别实现树

来源:互联网 发布:李兴华讲的java怎么样 编辑:程序博客网 时间:2024/05/28 15:58

javascript tree,check的实现

[javascript] view plaincopyprint?
  1. <head>   
  2. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />   
  3. <mce:script language="javascript"><!--  
  4.    
  5. function nodeClick(o)  
  6. {  
  7.     var obj, chk, disp, level, selectValue // 定义变量不说了吧  
  8.     obj = event.srcElement; // 将event的srcElement属性赋予obj,注:IE下。此属性和DOM的target属性兼容  
  9.     // srcElement是指发生事件的文档元素  
  10.   
  11.     if (obj == o) // 如果obj与传过来的参数o相等,则返回  
  12.         return;  
  13.   
  14.     // ----------------这一段的效果是将用户选择了哪几个checkbox显示出来  
  15.     // 如果元素是INPUT  
  16.     if (obj.tagName == "INPUT")  
  17.     {  
  18.         chk = obj.checked; // 将元素的checked值赋予chk,true or false  
  19.         // 取得input元素的父元素的样式的第2个字符,即下面的内联样式表中的id为tree,class为l1,l2,l3,l4的那些东西,取得值为1,2,3,4  
  20.         level = parseInt(obj.parentElement.className.substring(1));  
  21.         // 遍历input的父层所有相邻元素  
  22.   
  23.         while (obj.parentElement.nextSibling && parseInt(obj.parentElement.nextSibling.className.substring(1)) > level)  
  24.         {  
  25.             obj = obj.parentElement.nextSibling.all.tags("INPUT")[0]; // 又通过父元素找父下面的input子元素  
  26.             obj.checked = chk; // 赋予值,true or false  
  27.         }  
  28.   
  29.         // 作为最上端显示用,不过个人觉得直接用"selectedText"这样写不太严格  
  30.         selectedText.innerHTML = "U have selected: <b>" + getTreeValue() + " </b>"// 调用了getTreeValue()方法,下有解释  
  31.   
  32.         return;  
  33.     }  
  34.   
  35.     // 如果元素不存在相邻节点了,则返回  
  36.     if (!obj.nextSibling)  
  37.         return;  
  38.   
  39.     // ----------------这一段的效果是折叠树  
  40.     disp = obj.nextSibling.style.display != "none" ? "none" : "block"// 如果相邻节点的style下的display属性不等于none,则  
  41.   
  42.     // 将它(display)设为none,否则设为block  
  43.     level = parseInt(obj.className.substring(1));  
  44.   
  45.     // 遍历obj的相邻节点  
  46.     while (obj.nextSibling && parseInt(obj.nextSibling.className.substring(1)) > level)  
  47.     {  
  48.         obj = obj.nextSibling;  
  49.         obj.style.display = disp; // 设display属性,显示或折叠起来  
  50.     }  
  51. }  
  52.   
  53. // 此函数为取得已选择的节点,已选择的就把checkbox的值存入数组中  
  54. function getTreeValue()  
  55. {  
  56.     var val = [];  
  57.     var objs = document.getElementById("tree").all.tags("INPUT");  
  58.   
  59.     for (var i = 0; i < objs.length; i++)  
  60.         if (objs[i].checked)  
  61.             val.push(objs[i].value);  
  62.   
  63.     return val.join(",");  
  64. }  
  65.   
  66.           
  67. // --></mce:script>   
  68.         <mce:style><!--  
  69.    
  70.             * {   
  71.                 font-size: 9.5pt;   
  72.             }   
  73.              
  74.             #tree div {   
  75.                 height: 16px;   
  76.                 background-repeat: no-repeat;   
  77.                 padding-top: 2px;   
  78.                 padding-left: 20px;   
  79.                 cursor: default;   
  80.             }   
  81.              
  82.             #tree .l1, .l2, .l3 {   
  83.                 background-image: url('folder.gif');   
  84.             }   
  85.              
  86.             #tree .l4 {   
  87.                 background-image: url('file.png');   
  88.             }   
  89.              
  90.             #tree .l1 {   
  91.                 background-position: 2 0%;   
  92.             }   
  93.              
  94.             #tree .l2 {   
  95.                 background-position: 52 0%;   
  96.             }   
  97.              
  98.             #tree .l3 {   
  99.                 background-position: 64 0%;   
  100.             }   
  101.              
  102.             #tree .l4 {   
  103.                 background-position: 80 0%;   
  104.             }   
  105.              
  106.             #tree input {   
  107.                 margin: -2px;   
  108.                 margin-right: 20px;   
  109.             }   
  110.           
  111. --></mce:style><style mce_bogus="1">   
  112.             * {   
  113.                 font-size: 9.5pt;   
  114.             }   
  115.              
  116.             #tree div {   
  117.                 height: 16px;   
  118.                 background-repeat: no-repeat;   
  119.                 padding-top: 2px;   
  120.                 padding-left: 20px;   
  121.                 cursor: default;   
  122.             }   
  123.              
  124.             #tree .l1, .l2, .l3 {   
  125.                 background-image: url('folder.gif');   
  126.             }   
  127.              
  128.             #tree .l4 {   
  129.                 background-image: url('file.png');   
  130.             }   
  131.              
  132.             #tree .l1 {   
  133.                 background-position: 2 0%;   
  134.             }   
  135.              
  136.             #tree .l2 {   
  137.                 background-position: 52 0%;   
  138.             }   
  139.              
  140.             #tree .l3 {   
  141.                 background-position: 64 0%;   
  142.             }   
  143.              
  144.             #tree .l4 {   
  145.                 background-position: 80 0%;   
  146.             }   
  147.              
  148.             #tree input {   
  149.                 margin: -2px;   
  150.                 margin-right: 20px;   
  151.             }   
  152.         </style>   
  153.     </head>   
  154.     <body>   
  155.         <div id="selectedText">   
  156.                 
  157.         </div>   
  158.         <div id="tree" style="width:300px;height:450px;border:1px outset #EEEEEE;padding-top:2px;overflow-x:hidden;overflow-y:scroll;display:inline" onmouseover="javascript:var obj=event.srcElement;if(obj!=this)obj.style.backgroundColor='#f3f6ff';" onmouseout="javascript:var obj=event.srcElement;if(obj!=this)obj.style.backgroundColor='';" onclick="javascript:nodeClick(this)">   
  159.             <div class="l1">   
  160.                 请选择部门   
  161.             </div>   
  162.             <div class="l2">   
  163.                   <input type="checkbox" name="dept" value="申银万国">申银万国   
  164.             </div>   
  165.             <div class="l3">   
  166.                    <input type="checkbox" name="dept" value="经纪管理总部">经纪管理总部   
  167.             </div>   
  168.             <div class="l4">   
  169.                     <input type="checkbox" name="dept" value="上海余姚国债">上海余姚国债   
  170.             </div>   
  171.             <div class="l4">   
  172.                     <input type="checkbox" name="dept" value="上海新昌路证券营业部">上海新昌路证券营业部   
  173.             </div>   
  174.             <div class="l4">   
  175.                     <input type="checkbox" name="dept" value="上海莘庄证券营业部">上海莘庄证券营业部   
  176.             </div>   
  177.             <div class="l4">   
  178.                     <input type="checkbox" name="dept" value="上海中华路证券营业部">上海中华路证券营业部   
  179.             </div>   
  180.             <div class="l4">   
  181.                     <input type="checkbox" name="dept" value="上海瞿溪路营业部">上海瞿溪路营业部   
  182.             </div>   
  183.             <div class="l4">   
  184.                     <input type="checkbox" name="dept" value="上海东体育会路营业部">上海东体育会路营业部   
  185.             </div>   
  186.             <div class="l4">   
  187.                     <input type="checkbox" name="dept" value="上海奉贤证券营业部">上海奉贤证券营业部   
  188.             </div>   
  189.             <div class="l4">   
  190.                     <input type="checkbox" name="dept" value="上海福州路证券营业部">上海福州路证券营业部   
  191.             </div>   
  192.             <div class="l4">   
  193.                     <input type="checkbox" name="dept" value="上海余姚路证券营业部">上海余姚路证券营业部   
  194.             </div>   
  195.             <div class="l4">   
  196.                     <input type="checkbox" name="dept" value="上海虹古路证券营业部">上海虹古路证券营业部   
  197.             </div>   
  198.             <div class="l4">   
  199.                     <input type="checkbox" name="dept" value="上海龙茗路证券营业部">上海龙茗路证券营业部   
  200.             </div>   
  201.             <div class="l4">   
  202.                     <input type="checkbox" name="dept" value="上海金山证券营业部">上海金山证券营业部   
  203.             </div>   
  204.             <div class="l4">   
  205.                     <input type="checkbox" name="dept" value="上海洛川东路营业部">上海洛川东路营业部   
  206.             </div>   
  207.             <div class="l3">   
  208.                    <input type="checkbox" name="dept" value="银证通部门">银证通部门   
  209.             </div>   
  210.             <div class="l4">   
  211.                     <input type="checkbox" name="dept" value="银证通结算机构">银证通结算机构   
  212.             </div>   
  213.             <div class="l3">   
  214.                    <input type="checkbox" name="dept" value="经纪管理总部">经纪管理总部   
  215.             </div>   
  216.         </div>   
  217.     </body>   
  218. </html>  

 

JQUERY 实现无限极TREEVIEW

 

第一步:下载JQUERY和TREEVIEW插件。
         JQUERY:http://jquery.bassistance.de/dist/jquery.js
         TREEVIEW:http://jquery.bassistance.de/treeview/jquery.treeview.zip(注意:解压后里面的DEMO是不能正常显示的,因为缺少jquery.js。大家下载下来放到相应目录即可)
        
         第二步:创建一个HTML文件
         因为我们要利用一些图片资源,所以就在jquery.treeview.zip解压以后的目录里面创建。
         例如我们创建一个treeview.html文件。用你喜欢的编辑器写以下的代码
        

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
        <title>TREEVIEW</title>
        这里是引入jquery.js文件,我上面已经提过原来的压缩包是没有的,下载以后复制进去即可。
        <script type="text/javascript" src="jquery.js"></script>
        这里是引入treeview插件
        <script type="text/javascript" src="jquery.treeview.js"></script>
        下面这个是jquery的语法格式,不懂的可以到上面看我给的那些入门资料。
        <script type="text/javascript">
        $(function(){
        $("ul").Treeview();
       
        });
        </script>
        以下是一些CSS样式,这里是必须的。大家可以根据自己的喜好来改它的外观,这也是我特别欣赏       的地方
        <style type="text/css">
   
    .treeview, .treeview ul {
    padding: 0;
    margin: 0;
    list-style: none;
}   

.treeview li {
    margin: 0;
    padding: 4px 0 3px 20px;
}

.treeview li { background: url(images/tv-item.gif) 0 0 no-repeat; }
.treeview .collapsable { background-image: url(images/tv-collapsable.gif); }
.treeview .expandable { background-image: url(images/tv-expandable.gif); }
.treeview .last { background-image: url(images/tv-item-last.gif); }
.treeview .lastCollapsable { background-image: url(images/tv-collapsable-last.gif); }
.treeview .lastExpandable { background-image: url(images/tv-expandable-last.gif); }

    </style>
       
   
    </head>
    <body>
    
     大家可以根据自己的要求改下面的这些代码,只要结构按照html语言里的列表结构即可。
<ul>  <li>Item 1    <ul>      <li>Item 1.1</li>    </ul>  </li>  <li class="closed">Item 2 (如果CLASS指定了closed,那么他默认是关闭的)    <ul>      <li>Item 2.1        <ul>          <li>Item 2.1.1</li>          <li>Item 2.1.2</li>        </ul>      </li>      <li>Item 2.2</li>    </ul>  </li>  <li>Item 3</li></ul>


    </body>
</html>

 

jquery.treeview使用笔记

正好项目中用到了JQuery,所以就在网上找依赖JQuery的JS树,最终选择了jquery.treeview.js,原因之一,它是JQuery官方发布的JS库,另一方面,看了一下它的文档,使用起来也是很简单的。经过一个小时的研究,终于搞定,现把它的使用方法做个简要的说明,以做笔记。

        要使用jquery.treeview.js,97xxoo当然第一步是要把它下载下来,放入自己的工程中,然后在页面文件中引进jquery.js,jquery.cookie.js,jquery.treeview.js,jquery.treeview.async.js四个库文件,其中最后一个是要使用异步加载结点的时候,要用到的,我的项目中已经用到了这个功能,在初始化树的时候,只加载顶层的数据,当点击顶层结点的时候,就去干才会去加载下一层的结点,所有的数据都是通过ajax去后台取得到数据。

        将库文件引入后,下一步就是要定义一个列表UL:如这样:
<ul id="ProductTypes">
        </ul>
树数据将会加载到这个UL里面
<script type="text/javascript">
$(document).ready(function(){
  //alert('ready');
  $("#ProductTypes").treeview({
   url: "/FetchProductTypeServlet"
  });
  //alert('ready111');
});
</script>
这里面的意思就是当文档加载完成后,草榴社区向后台FetchProductTypeServlet获取数据,注意后台输出的数据必须是json格式的数据。

下一步就是后台FetchProductTypeServlet的数据输出部分了:

  response.setHeader("Cache-Control", "no-cache");
  response.setContentType("text/json;charset=UTF-8");
  try {
   request.setCharacterEncoding("utf-8");
  } catch (UnsupportedEncodingException e1) {
   e1.printStackTrace();
  }
要将contenttype设置为"text/json",第一次加载初始数据的时候,会向这个FetchProductTypeServlet传递一个get参数:root=source,所以后台可以判断root参数是否是source,如果是source,则代表是第一次加载数据,如果不是source,则root参数传递的則是树结点的id.

数据格式如下:
[
{
  "text": "1. Pre Lunch (120 min)",
  "expanded": true,
  "classes": "important",
  "children":
  [
   {
    "text": "1.1 The State of the Powerdome (30 min)"
   },
    {
    "text": "1.2 The Future of jQuery (30 min)"
   },
    {
    "text": "1.2 jQuery UI - A step to richnessy (60 min)"
   }
  ]
},
{
  "text": "2. Lunch  (60 min)"
},
{
  "text": "3. After Lunch  (120+ min)",
  "children":
  [
   {
    "text": "3.1 jQuery Calendar Success Story (20 min)"
   },
    {
    "text": "3.2 jQuery and Ruby Web Frameworks (20 min)"
   },
    {
    "text": "3.3 Hey, I Can Do That! (20 min)"
   },
    {
    "text": "3.4 Taconite and Form (20 min)"
   },
    {
    "text": "3.5 Server-side JavaScript with jQuery and AOLserver (20 min)"
   },
    {
    "text": "3.6 The Onion: How to add features without adding features (20 min)",
    "id": "36",
    "hasChildren": true
   },
    {
    "text": "3.7 Visualizations with JavaScript and Canvas (20 min)"
   },
    {
    "text": "3.8 ActiveDOM (20 min)"
   },
    {
    "text": "3.8 Growing jQuery (20 min)"
   }
  ]
}
]

格式说明:上面的1. Pre Lunch (120 min) 结点中:"expanded": true 代表这个结点下的child是展开的,children则是子结点的数据,节点3. After Lunch  (120+ min)有8个子结点,其中子结点中有一个结点3.6 The Onion: How to add features without adding features (20 min),有一个id属性,同时hasChildren:true,表示其下面又有子结点,并且会向FetchProductTypeServlet传递参数为:root=id值,具体到这里就是root=36,那么点击这个结点的时候,后台就会接收到root=36这个值,然后我们就在具体应用中,通过数据库查询或者其它方式找到相对应的数据,然后将这些数据构造成treeview所需要的json数据,也即是上面所示格式的数据。

后台FetchProductTypeServlet代码如下:
public class FetchProductTypeServlet extends HttpServlet {

ProdTypeDao prodTypeDao = null;

@Override
public void init() throws ServletException {
  // TODO Auto-generated method stub
  prodTypeDao = new ProdTypeDao();
  super.init();
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request,response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setHeader("Cache-Control", "no-cache");
  response.setContentType("text/json;charset=UTF-8");
  try {
   request.setCharacterEncoding("utf-8");
  } catch (UnsupportedEncodingException e1) {
   e1.printStackTrace();
  }

  PrintWriter out = response.getWriter();
  
  String root = request.getParameter("root");
  System.out.println("root:"+root);

  try {
   String output = generateNodeString(root);
   System.out.println("output======"+output);
   out.print(generateNodeString(root));
  } catch (ActionException e) {
   e.printStackTrace();
   RequestDispatcher rd = null;
   request.setAttribute("ActionException", e);
   rd = request.getRequestDispatcher("/common/error.jsp");
   rd.forward(request, response);
  }
  
  out.flush();
  out.close();
}

private String generateNodeString(String id) throws ActionException {  
  if(id == null){
   return "";
  }else if(id.equalsIgnoreCase("source")){   
   return generateInitTreeString();
  }else{
   return generateTreeChildNodeString(Integer.parseInt(id));
  }
}

private String generateTreeChildNodeString(int typeId) throws ActionException{
  int typeId_ = typeId ;
  Connection conn = null;

  //hasSubItem
  StringBuilder sb = new StringBuilder();
  sb.append("[");
  
  ArrayList<ProdTypeBean> l;
  try {
   l = prodTypeDao.fetchSubItem(typeId_);
  } catch (ActionException e) {   
   e.printStackTrace();
   throw new ActionException("generateTreeChildNodeString err","generateTreeChildNodeString","generateTreeChildNodeString err");
  }
  int i = 0;
  for(Iterator it = l.iterator();it.hasNext();i++){
   if(i>0){
    sb.append(",");
   }
   ProdTypeBean item = (ProdTypeBean)it.next();
   sb.append(generateNodeString(item));
  }
  
  sb.append("]");
  return sb.toString();
}

private String generateLinkString(ProdTypeBean item){
  return "<a href='../../CommendProduct?typeId="+item.getPT_ID()+"' target='main' >"+item.getPT_NAME()+"</a>";
}

private String generateNodeString(ProdTypeBean item){
  StringBuilder sb = new StringBuilder();
  sb.append(" {");
  sb.append("  /"text/": /""+generateLinkString(item)+"/"");
  
  try {
   if(prodTypeDao.hasSubItem(item.getPT_ID())){
    sb.append(",  /"id/":/""+item.getPT_ID()+"/"");
    sb.append(",  /"hasChildren/":true");
   }
  } catch (ActionException e) {   
   e.printStackTrace();
   return "{}";
  }
  sb.append(" }");  
  return sb.toString();
}

private String generateInitTreeString() throws ActionException{
  int typeId_ = 0 ;
  Connection conn = null;

  //hasSubItem
  StringBuilder sb = new StringBuilder();
  sb.append("[");
  
  ArrayList<ProdTypeBean> l;
  try {
   l = prodTypeDao.fetchSubItem(typeId_);
  } catch (ActionException e) {   
   e.printStackTrace();
   throw new ActionException("generateInitTreeString err","generateInitTreeString err","generateInitTreeString err");
  }
  int i = 0;
  for(Iterator it = l.iterator();it.hasNext();i++){
   if(i>0){
    sb.append(",");
   }
   ProdTypeBean item = (ProdTypeBean)it.next();
   sb.append(generateNodeString(item));
  }
  
  sb.append("]");  
  return sb.toString();
}

}


 jQuery treeview在JSP中的应用

1. 配置,其中jquery.jsjquery.cookie.js要用jquery-treeview/ lib/下的

jqurey

2. navigation.jsp

<%@ pagelanguage="java"contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglibprefix="sql"uri="http://java.sun.com/jsp/jstl/sql"%>

<%@ taglibprefix="fmt"uri="http://java.sun.com/jsp/jstl/fmt"%>

<!DOCTYPEhtmlPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">

<html>

    <head>

       <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">

       <title>Insert title here</title>

       <linkrel="stylesheet"href="css/jquery.treeview.css"/>

       <linkrel="stylesheet"href="css/screen.css"/>

 

       <scriptsrc="javascript/jquery.js"type="text/javascript"></script>

       <scriptsrc="javascript/jquery.cookie.js"type="text/javascript"></script>

       <scriptsrc="javascript/jquery.treeview.js"type="text/javascript"></script>

       <scripttype="text/javascript">

           $(document).ready(function(){

              $("#navigation").treeview({

                  control:"#treecontrol",

                  persist: "location",

                  collapsed: true

              });

           });

       </script>

    </head>

    <body>

       <h1id="banner">

           <a

              href="http://bassistance.de/jquery-plugins/jquery-plugin-treeview/">jQuery

              Treeview Plugin</a> Demo

       </h1>

       <divid="main">

           <ahref=".">Main</a>

           <h4>

              Sample - navigation

           </h4>

           <divid="treecontrol">

              <atitle="Collapse the entire tree below"href="#"><img

                     src="images/minus.gif"/> Collapse All</a>

              <atitle="Expand the entire tree below"href="#"><img

                     src="images/plus.gif"/> Expand All</a>

              <a

                  title="Toggle the tree below, opening closed branches, closing open branches"

                  href="#">Toggle All</a>

           </div>

           <ulid="navigation">

              <c:forEachvar="list"items="${list}">

                  <li>

                     ${list.item}

                     <c:iftest="${emptylist.itemsForItemId == false}">

                         <ul>

                            <c:forEachvar="list1"items="${list.itemsForItemId}">

                                <li>

                                   ${list1.item}

                                </li>

                            </c:forEach>

                         </ul>

                     </c:if>

                  </li>

              </c:forEach>

           </ul>

       </div>

    </body>

</html>

 

3. TestController

@Controller

publicclass TestController {

 

    @Autowired

    TestDao testDao;

 

    @RequestMapping("/navigation.html")

    public String navigation(HttpServletRequest request) {

       request.setAttribute("list",testDao.findTopItem());

       return"navigation";

    }

 

    @RequestMapping("/async.html")

    public String async(HttpServletRequest request) {

       return"async";

    }

}

 

 

4. TestDaoImpl

@Repository("testDao")

publicclass TestDaoImplextends HibernateBaseDaoimplements TestDao {

    @SuppressWarnings("unchecked")

    public List<Item> findTopItem() {

       return getHibernateTemplate().find("from Item where itemLevel = 1");

    }

 

    @SuppressWarnings("unchecked")

    public List<Item> find(Long itemId) {

       return getHibernateTemplate().find("from Item a where a.itemId = ?",

              itemId);

    }

 

    @SuppressWarnings("unchecked")

    public List<Item> findSubItem(Long itemId) {

       List<Item> list = new ArrayList();

       List<Item> itemList = find(itemId);

 

       Set<Item> subList = itemList.get(0).getItemsForItemId();

       for (Item item2 : subList) {

           list.add(item2);

       }

       return list;

    }

 

    public Boolean hasSubItem(Long itemId) {

       Boolean ret = false;

       List<Item> subList = findSubItem(itemId);

       if (!subList.isEmpty()) {

           ret = true;

       }

       return ret;

    }

 

}

 

原创粉丝点击