博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

json treeview控件

Posted on 2012-06-15 17:21  bw_0927  阅读(997)  评论(0)    收藏  举报

http://www.dynamicdrive.com/dynamicindex1/treeview/index.htm

http://www.cnblogs.com/xuanye/archive/2009/10/26/1590250.html

http://hegz.iteye.com/blog/645905

http://peirenlei.iteye.com/blog/304999

http://www.zhuoda.org/irini/83891.html

http://blog.csdn.net/wangxiaoyan1988/article/details/6198247

http://www.gafish.net/archives/854

 

Description: jQuery TreeView Menu brings together all the most practical features requested in a Tree Menu into one awesome menu script. The markup for the menu is simply a HTML list before the script transforms it into a TreeView Menu that supports the following:

  • Three different ways to specify the initial state of the tree nodes:
    • 1) All collapsed by default
    • 2) All collapsed except ones with CSS class "open", or
    • 3) All expanded except ones with CSS class "closed".
  • Ability to specify that only one tree branch is open at any time, collapsing any previous open branches.
  • Two types of persistence supported:
    • 1) "Cookie" based, persisting last tree state before user navigates away from page.
    • 2) "Location" based, expanding the branch or node with an "href" value that matches that of the current page (location.href). This lets you expand a particular branch that corresponds to the current page.
  • Supports optional animation with variable speed.
  • Controls can be added that collapses, expands, or toggles all nodes within a tree.
  • Supports optional asynchronous loading of the tree, so inner branches are loaded on demand based on JSON data returned from the server.

Now this is a Tree Menu!

Demos

Demo #1:

 

 

Notes:

  • All nodes collapsed explicitly by default, though overwritten by persistence feature below.
  • Only one node allowed open at any time.
  • Animation disabled..
  • "Location" persistence enabled, causing the branch with an "href" value matching that of the current page (location.href) to be expanded by default. In the demo above, that is "Item 1.0.0".

Configuration code:

$("#navigation").treeview({
 collapsed: true,
 unique: true,
 persist: "location"
});

Demo #2:

 

Click here to add a New Folder node to the end of the existing tree

  •  
    Folder 1
    • Item 1.1
  •  
    Folder 2
    •  
      Subfolder 2.1
      • File 2.1.1
      • File 2.1.2
    • File 2.2
  • File 4

 

Notes:

  • No Nodes collapsed explicitly. "Folder 3" is manually closed then by giving its LI element a "closed" CSS class.
  • Animation enabled, speed is "normal".
  • "Cookie" persistence enabled, causing the current tree state to be persisted.
  • Dynamically adding a sub tree to the existing tree demonsrated.

Configuration code:

$("#browser").treeview({
 animated:"normal",
 persist: "cookie"
});

$("#samplebutton").click(function(){
 var branches = $("<li><span class='folder'>New Sublist</span><ul>" + 
"<li><span class='file'>Item1</span></li>" + 
"<li><span class='file'>Item2</span></li></ul></li>").appendTo("#browser");
 $("#browser").treeview({
  add: branches
 });
});

Demo #3:

 

 

Notes:

  • All nodes collapsed explicitly by default.
  • Animation enabled, speed is "fast".
  • Tree state persistence off.
  • Toggle all links added, to easily expand, contract, and toggle all branches within the tree.

Configuration code:

$("#red").treeview({
 animated: "fast",
 collapsed: true,
 control: "#treecontrol",
 }
});

Directions

Directions: Simply download jquery.treeview.zip, and refer to the demo page for the full source of the above 3 demos.

Setting Up a Tree View on your page

The markup for a Tree View Menu on your page should simply be a valid HTML list with a unique ID and CSS class that styles it:

<ul id="mymenu" class="filetree">
"
"
<ul>

Then, transform it into a Tree View Menu by calling the function Treeview(), invoked when the page has loaded to ensure the menu exists at time of invocation code in bold):

$(document).ready(function(){

 $("#mymenu").treeview({
  collapsed: true,
  other options...
 });

});

Note the outer most container code in bold- always define your TreeView configuration code(s) inside it so they are invoked only when the page has loaded.

treeview() function options

The main Treeview() function used to render a tree supports the following options passed in as parameters, all of which are optional:

ParameterDescription
animated: speed Sets the animation speed. Valid values are one of the strings "slow", "normal", "fast", or an integer representing milliseconds, such as 1000 for 1 second animation.

To disable animation, remove this option entirely.

collapsed: true|false Sets whether all nodes should be collapsed by default.

Defaults to false.

unique: true|false Sets whether only one tree node can be open at any time, collapsing any previous open nodes.

Defaults to false.

persist: "location|cookie" Persists the tree's expand/collapse state in one of two ways:
  1. "location": looks within all tree nodes with link anchors that match the document's current URL (location.href), and if found, expands that node (including its parent nodes). Great for href-based state saving.
  2. "cookie": Saves the current state of the tree on each click to a cookie and restores that state on page load.

To disable persistence, remove this option entirely.

cookieId: string The desired custom cookie name to use when persisting via persist: "cookie".

$("#mytree").treeview({
 persist: "cookie",
 cookieId: "rememberme"
});

Defaults to interval value when this option is not defined.

control: jQuery selector Specifies the HTML element(s) on the page that will contain links to collapse(收缩), expand(展开), and toggle(收缩已经展开的,展开已经收缩的) all nodes within the tree, in that order. The valid value is a jQuery selector, most commonly, "#mycontainerid", where "mycontainerid" should be the ID of the control element. For example:

The HTML:

<div id="masstoggler">
<a title="Collapse entire tree" href="#"> Collapse All</a> | 
<a title="Expand entire tree" href="#"> Expand All</a> | 
<a title="Toggle the tree below" href="#">Toggle All</a>
</div>

The configuration code:

$("#mytree").treeview({
 collapsed: true,
 control: "#masstoggler"
});

Order is important when specifying the toggler links within the control element- the first link will always be assigned the "collapse all" behaviour, the second link the "expand all" behaviour, and finally, the last the "toggle all" behaviour.

Make sure the option "unique: true" is NOT set when setting the "control" option, or the links will appear as if they are not working!

toggle: callbackfunction Callback when toggling a branch. Arguments: "this" refers to the LI element with its sub UL either shown or hidden. Works only with speed option set (set speed: 1 to enable callback without animations):

$("mytree").treeview({
 toggle: function() {
  var subul=this.getElementsByTagName("ul")[0]
  if (subul.style.display=="block")
   alert("You've opened this Folder!")
  }
})

To disable toggle, remove this option entirely.

add: jQuery selector Extends the tree with additional nodes by adding them somewhere within the existing tree (as specified by the jQuery selector), then refreshes the tree to account for the new nodes. The jQuery selector must point to node(s) within the tree that already exist.

The following defines a link (with ID "#samplelink) on the page that when clicked on adds a new folder branch to the top of an existing tree:

$("#sampletree").treeview({collapsed: true});

$("#samplelink").click(function(){
 var topbranch = $("<li><span class='folder'>New Sublist</span><ul>" + 
"<li><span class='file'>Item1</span></li>" + 
"<li><span class='file'>Item2</span></li></ul></li>").prependTo("#sampletree");

 $("#sampletree").treeview({
  add: topbranch
 });

});

Demo:

Add New Folder

 

Where the new branch gets added within the tree depends on the code in bold. Here are some examples:

//adds new branch to the very end of the entire tree
var bottombranch=$('new_branch_html').appendTo("#sampletree");

//adds new branch to the top of the first Folder ("Folder 1")
var folder1topbranch=$('new_branch_html').prependTo("#sampletree ul:eq(0)");

//adds new branch to the end of the folder UL with id="#mybranch"
var mybranchbottombranch=$('new_branch_html').appendTo("#sampletree #mybranch");

In other words, use a valid jQuery selector to identify the UL within the tree to add the new branch to.

prerendered: true/false If set to true, skips parsing of branches within the tree with explicit classes defined, or DIVs within three with class "hitarea". This makes the tree more obtrusive, but speeds up render times for large trees significantly. For branches that are not parsed by the script, it is up to you to manually define their initial states using CSS, as the script will not do this for you (ie: setting "collapsed: true" has no effect on these branches):

Portion HTML of a sample tree with prerendered enabled:

"
<li class="expandable"><div class="hitarea expandable-hitarea"></div><a href="#"><strong>Home</strong></a>
<ul style="display: none;">
<li><a href="?/enewsletters/index.cfm">Airdrie eNewsletters </a></li>
<li><a href="?/index.cfm">Airdrie Directories</a></li>
<li><a href="?/economic_development/video/index.cfm">Airdrie Life Video</a></li>

Defaults to false.

url: "source.php" If defined, starts with an empty tree, then asynchronously adds branches to the tree when requested based on data returned from the server (in JSON format), specifically the specified server side script (ie: "source.php").

Sample initial HTML Markup on page:

<ul id="asynctree">
</ul>

Sample configuration code:

$("#asynctree").treeview({
url: "source.php"
})

See "Async Treeview example" for more info on this option.

Specifying which branches within the tree should be expanded or contracted by default

When you define a TreeView Menu on your page, there are 3 ways in general to specify the initial states of the branches within it. To specify that all branches be collapsed by default, just define the "collapsed: true" option within the configuration code:

$("#navigation").treeview({
 collapsed: true,
 unique: true,
 persist: "location"
});

To specify that all branches be collapsed except particular ones, still define "collapsed: true" above, but inside the tree's HTML, insert the CSS class "open" inside the parent LI of the branch that should be explicitly open:

<li class="open"><a href="#">Folder 3 (open by default)</a>
 <ul>
  <ll>Item 3.1</li>
  <ll>Item 3.1</li>
  <ll>Item 3.1</li>
 </ul>
</li>
"
"

To specify that all branches appear as they normally would except for certain ones that should be collapsed by default, first, undeclare "collapsed: true" from the configuration code, then insert the CSS class "closed" inside the parent LI of the branch that should be explicitly closed:

<li class="closed"><a href="#">Folder 3 (open by default)</a>
 <ul>
  <ll>Item 3.1</li>
  <ll>Item 3.1</li>
  <ll>Item 3.1</li>
 </ul>
</li>
"
"

Table Of Contents

This script consists of an index page plus 1 supplementary page:

 

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

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

        将库文件引入后,下一步就是要定义一个列表UL:如这样:

Html代码  收藏代码
  1. <ul id="categorys"></ul>  

 


 树数据将会加载到这个UL里面

Js代码  收藏代码
  1. <script type="text/javascript">  
  2.  $(document).ready(function(){  
  3.   $("#categorys").treeview({  
  4.    url: "category!ajaxTreeView"  
  5.   });  
  6.  });  
  7. </script>  

 


这里面的意思就是当文档加载完成后,向后台CategoryAction获取数据,注意后台输出的数据必须是json格式的数据。

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

Java代码  收藏代码
  1. response.setHeader("Cache-Control""no-cache");  
  2. response.setContentType("text/json;charset=UTF-8");  
  3. try {  
  4.  request.setCharacterEncoding("utf-8");  
  5. catch (UnsupportedEncodingException e1) {  
  6.  e1.printStackTrace();  
  7. }  

 


 要将contenttype设置为"text/json",第一次加载初始数据的时候,会向这个CategoryAction传递一个get参数:root=source,所以后台可以判断root参数是否是source,如果是source,则代表是第一次加载数据,如果不是source,则root参数传递的則是树结点的id.
 
 数据格式如下:

Json代码  收藏代码
  1. [  
  2.  {  
  3.   "text""1. Pre Lunch (120 min)",  
  4.   "expanded": true,  
  5.   "classes""important",  
  6.   "children":  
  7.   [  
  8.    {  
  9.     "text""1.1 The State of the Powerdome (30 min)"  
  10.    },  
  11.     {  
  12.     "text""1.2 The Future of jQuery (30 min)"  
  13.    },  
  14.     {  
  15.     "text""1.2 jQuery UI - A step to richnessy (60 min)"  
  16.    }  
  17.   ]  
  18.  },  
  19.  {  
  20.   "text""2. Lunch  (60 min)"  
  21.  },  
  22.  {  
  23.   "text""3. After Lunch  (120+ min)",  
  24.   "children":  
  25.   [  
  26.    {  
  27.     "text""3.1 jQuery Calendar Success Story (20 min)"  
  28.    },  
  29.     {  
  30.     "text""3.2 jQuery and Ruby Web Frameworks (20 min)"  
  31.    },  
  32.     {  
  33.     "text""3.3 Hey, I Can Do That! (20 min)"  
  34.    },  
  35.     {  
  36.     "text""3.4 Taconite and Form (20 min)"  
  37.    },  
  38.     {  
  39.     "text""3.5 Server-side JavaScript with jQuery and AOLserver (20 min)"  
  40.    },  
  41.     {  
  42.     "text""3.6 The Onion: How to add features without adding features (20 min)",  
  43.     "id""36",  
  44.     "hasChildren": true  
  45.    },  
  46.     {  
  47.     "text""3.7 Visualizations with JavaScript and Canvas (20 min)"  
  48.    },  
  49.     {  
  50.     "text""3.8 ActiveDOM (20 min)"  
  51.    },  
  52.     {  
  53.     "text""3.8 Growing jQuery (20 min)"  
  54.    }  
  55.   ]  
  56.  }  
  57. ]  

 

 

格式说明:上面的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数据,也即是上面所示格式的数据。

 

 

后台CategoryAction代码如下:

Java代码  收藏代码
  1. public String ajaxTreeView(){  
  2.     Struts2Utils.renderText(categoryHelper.generateJTVJsonString());  
  3.     return null;  
  4. }  

 

CategoryHelper代码如下:

Java代码  收藏代码
  1. package com.prl.action.admin.helper;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.servlet.http.HttpServletRequest;  
  6.   
  7. import org.apache.commons.logging.Log;  
  8. import org.apache.commons.logging.LogFactory;  
  9. import org.springframework.beans.factory.annotation.Autowired;  
  10. import org.springframework.stereotype.Repository;  
  11. import org.springside.modules.web.struts2.Struts2Utils;  
  12.   
  13. import com.prl.entity.Category;  
  14. import com.prl.service.CategoryManager;  
  15. import com.prl.service.jdbc.CategoryJdbcUtil;  
  16.   
  17. @Repository  
  18. public class CategoryHelper {  
  19.     private static final Log log = LogFactory.getLog(CategoryHelper.class);  
  20.     @Autowired  
  21.     public CategoryManager categoryManager;  
  22.     @Autowired  
  23.     public CategoryJdbcUtil categoryJdbcUtil;  
  24.   
  25.     // ========================= 产生jquery.treeview的jsonstring=================//  
  26.     public String generateJTVJsonString() {  
  27.         log.info("generateJTVJsonString start .....");  
  28.         HttpServletRequest request = Struts2Utils.getRequest();  
  29.         String id = request.getParameter("root");  
  30.         log.info("id:"+id);  
  31.         String output = "";  
  32.         if (id == null) {  
  33.             return "";  
  34.         } else if (id.equalsIgnoreCase("source")) {  
  35.             output = generateInitTreeString();  
  36.         } else {  
  37.             output = generateTreeChildNodeString(Long.parseLong(id));  
  38.         }  
  39.         log.info("generateJTVJsonString end,return:"+output);  
  40.         return output;  
  41.     }  
  42.   
  43.     // 产生子节点jsonstring  
  44.     private String generateTreeChildNodeString(Long categoryId) {  
  45.         StringBuilder jsonString = new StringBuilder();  
  46.         jsonString.append("[");  
  47.   
  48.         List<Category> categorys = categoryManager  
  49.                 .findChildrenCategory(categoryId);  
  50.         if (categorys.isEmpty())  
  51.             return "";  
  52.         int i = 0;  
  53.         for (Category category : categorys) {  
  54.             if (i > 0) {  
  55.                 jsonString.append(",");  
  56.             }  
  57.             jsonString.append(toJSONString(category));  
  58.             i++;  
  59.         }  
  60.   
  61.         jsonString.append("]");  
  62.         return jsonString.toString();  
  63.     }  
  64.   
  65.     private String toJSONString(Category category) {  
  66.         StringBuilder sb = new StringBuilder();  
  67.         sb.append(" {");  
  68.         sb.append("  \"text\": \"" + generateLinkString(category) + "\"");  
  69.   
  70.         if (categoryJdbcUtil.hasChild(category)) {  
  71.             sb.append(",  \"id\":\"" + category.getCatId() + "\"");  
  72.             sb.append(",  \"hasChildren\":true");  
  73.         }  
  74.         sb.append(" }");  
  75.         return sb.toString();  
  76.     }  
  77.   
  78.     private String generateLinkString(Category category) {  
  79.         String link = "<a href='javascript:on_cat_click("+category.getCatId()+");' >" + category.getCatName() + "</a>";  
  80.         //link = category.getCatName();  
  81.         return link;  
  82.     }  
  83.   
  84.     private String generateInitTreeString() {  
  85.         StringBuilder jsonString = new StringBuilder();  
  86.         jsonString.append("[");  
  87.   
  88.         List<Category> categorys = categoryManager.getRoot();  
  89.         int i = 0;  
  90.         for (Category category : categorys) {  
  91.             if (i > 0) {  
  92.                 jsonString.append(",");  
  93.             }  
  94.             jsonString.append(toJSONString(category));  
  95.             i++;  
  96.         }  
  97.   
  98.         jsonString.append("]");  
  99.         return jsonString.toString();  
  100.     }  
  101.     // ==================== 产生jquery.treeview的jsonstring 结束=================//  
  102. }  

 

 

写完收功,希望能帮到正在使用这个treeview的朋友点小忙,自己以后再使用的时候,也可以再翻看一下这篇笔记,不至于搞忘记用法了。