Jquery樹形菜單插件之JsTree


環境:0.98版本。

0.98版本可以在官方下載,也可以在這里下載:http://files.cnblogs.com/china-li/jsTree.v.0.9.8.zip。

下載后,打開jsTree.v.0.9.8\reference\index.html,可以看到其詳細文檔。

 

一、引入文件

  需要引入的文件:

  • _lib/jquery.js
  • _lib/css.js
  • source/tree_component.js
  • source/tree_component.css

  必須先引入jquery文件。也可以直接引入_lib/_lib.js文件,這個文件包含了jquery.js  css.js還有cookie插件等。

 

二、如何創建

  創建樹,有兩種方式,通常用的是$('#demo1').tree({});

 

三、實例

  我略去了api和配置項的詳細講解,而是在示例中一一指明。

  首先,JsTree要獲取數據,數據的獲取形式大致三種:靜態,動態,ajax。

  1、靜態很好理解,就是原本就存在的數據。例如,一個原本就存在的html文檔:  

  <div id="demo1" class="demo tree tree-default" style="direction: ltr; ">
    <ul class="ltr">
        <li id="phtml_1" class="closed"><a href="#">Root node 1</a>
            <ul>
                <li id="phtml_2" class="leaf"><a href="#" style="background-image:url('../media/images/ok.png');">Custom icon</a></li>
                <li id="phtml_3" class="leaf"><a href="#">Child node 2</a></li>
                <li id="phtml_4" class="last leaf"><a href="#">Some other child node 111</a></li>
            </ul>
        </li>
        <li id="phtml_5" class="last leaf"><a href="#" class="">Root node 2</a></li>
    </ul>
  </div>

  當然,這個html文檔遵循了JsTree的規范,不是隨意的。我們利用這個原來存在的數據,直接就能生成樹:

$(function () {
    $("#demo1").tree();
});

  

  還有我們可以利用json靜態數據和xml靜態數據來實現樹:

$("#demo2").tree({
  data  : {
    type  : "json",
    json  : [ 
      { attributes: { id : "pjson_1" }, state: "open", data: "Root node 1", children : [
        { attributes: { id : "pjson_2" }, data: { title : "Custom icon", icon : "../media/images/ok.png" } },
        { attributes: { id : "pjson_3" }, data: "Child node 2" },
        { attributes: { id : "pjson_4" }, data: "Some other child node" }
      ]}, 
      { attributes: { id : "pjson_5" }, data: "Root node 2" } 
    ]
  }
});
$(function () {
    $("#demo3").tree({
      data  : {
        type  : "xml_nested", // or "xml_flat"
        xml  : '<root><item id="pxml_1" ><content><name ><![CDATA[Root node 1]]></name></content><item id="pxml_2" ><content><name icon="../media/images/ok.png" ><![CDATA[Custom icon]]></name></content></item><item id="pxml_3" ><content><name ><![CDATA[Child node 2]]></name></content></item><item id="pxml_4" ><content><name ><![CDATA[Some other child node]]></name></content></item></item><item id="pxml_5" ><content><name ><![CDATA[Root node 2]]></name></content></item></root>'
      }
    });
});

  只要在頁面上留id是demo2和demo3的div即可,里面不用有內容,一切都是JsTree自動加載的。

  解釋屬性:

  •   data      一個大配置項,里面配置數據有關的選項
  •   type  類型。可選值: json, xml_flat(平整的xml), xml_nested(嵌套的xml), predefined(預定義,如html)
  •   json,xml      數據源,如上顯示

 

  2、動態加載。就是從其他文件中加載數據,利用url配置即可。例如從服務端xml文件獲取數據:

$(function () {
    $("#demo4").tree({
      data  : {
        type  : "xml_flat", // or "xml_nested" or "json"
        url   : "1_xml_flat.xml"
      }
    });
});

  同樣,也可以從struts2的action中獲取xml,或者獲取json。

 

  3、ajax加載數據。這個是重點,涉及到的東西比較多。ajax動態加載的原理是,先加載頂級節點,當點擊頂級節點的時候,根據傳到后台的id獲取頂級節點的子節點集合。它不是一下子把所有的節點都加載,而是通過這種方式加載數據。這樣無疑是節省資源的做法,降低了服務器壓力,同時進入頁面的等待時間也大大降低。

  先看一下一個完整的例子,然后解釋屬性:

$(function(){
    $.ajaxSetup({cache:false});    //ajax信息不緩存
    $("#divForTree").tree({
        data:{
            type  : "json",
            url   : "<%=path%>/admin/doList.do",//每次獲得數據從這個鏈接  
            async : true,//動態加載數據  
            async_data : function(NODE) {
                    //請求數據時帶的參數列表,可通過getParameter獲得。
                    return {parentId : getId($(NODE))};
                }
            },
        lang : {
                loading : "目錄加載中..."    //加載的時候顯示
            },
        rules : {    
                multiple : 'ctrl'    //允許通過ctrl多選。
            },
        ui : {
                context:{    //右鍵菜單
                    visible:function(node,tree_obj){
                        return false;    //返回-1表示不可用;false表示不顯示    
                    }
                },
                theme_name : "classic"    //主題。themes下的四種主題
            },
        callback : {    //事件
                onselect : function(node) {
                    $.tree_reference('divForTree').toggle_branch($(node));
                },
                error : function(TEXT, TREE_OBJ) {
                    alert(TEXT);
                }
            }
    });
});

  先看大配置項:

  • data    數據
  • lang    標志
  • rules   規則
  • ui       界面
  • callback     回調函數,事件

  小配置項,都有注釋。文檔中則有詳細講解。我是在節點被選中的時候(onselect),讓節點打開或關閉。后台獲取的數據,前台使用getId()方法得到parentId。因為每個節點的id在數據庫中都是數字,而純數字不符合css命名規范,所以我在每個id上都加了一個‘n’。前台解析的時候,getId()方法如下:  

function getId(node){
    var id = node.attr('id');
    if(id){
        id = $.trim(id.substring(1));
    }else{
        id = 0;
    }
    return id;
}

  第一次,獲取的是0,顯示的是頂級節點。

 

  后台需要創建一個工具類,這個工具類依照JsTree規則:

public class JsTreeNode {
    public static String STATE_OPEN = "open";
    public static String STATE_CLOSED = "closed";

    private String id;
    private String state;
    private String data;
    private int hasChild;
    
       //...省略getter,setter
}

  在struts2的返回頁面,用標簽迭代,輸出json:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
[
<s:iterator  value="listNodes"  >
{"attributes":{"id":"${id}"}
<s:if test="hasChild == 1">
    ,"data":"${data}","state":"${state}","children":[{}]
</s:if>
<s:else>
    ,"data": { "title" : "${data}"/*,"icon":"http://www.cnblogs.com/style/test/img/st_node.gif"*/}
</s:else>}
    ,
</s:iterator>
]

  如果有子節點,則顯示state,如果沒有,則輸出title就行。后面注釋的icon是自定義的圖像,可有可無。

 

  其中,JsTree中有幾個api,比較重要:

$.tree_reference('demo1').selected    //前面是當前tree的引用,selected表示被選擇的節點
$.tree_reference('demo1').opened    //被打開的節點集合
$.tree_reference('demo1').selected_arr    //如果在rules下定義了允許多選,這個屬性才有用。表示被選擇的節點集合
$.tree_reference('demo1').refresh()    //刷新節點
open_branch($(node))    //模擬打開一個節點
close_branch(node)    //模擬關閉
open_all()        //打開所有
close_all()       //關閉所有 
rename()      //重命名
remove()     //刪除
next()     //獲得下一個節點
prev()     //前一個節點
parent()    //父節點
children()      //子節點集合
get_next()       //
get_prev()    //
get_left()       //
get_right()        //獲得選中節點的上下左右
cut()         //剪切
copy()        //復制
paste()       //粘貼

其他的,看文檔自己研究!

  

多一句:1.0使用插件形式來組合的,可以直接使用這個版本!

另外,推薦一個國產Tree插件:ZTree。

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM