前言:
最近的項目需要用到zTree樹,於是想將zTree樹總結一下。前段時間一直沒有時間總結,趁國慶還有這麼點時間,總結一下。zTree樹控制項是基於Jquery的,官方提供了很好的API文檔和Demo
1.協助文檔和API
zTree的協助文檔和API都是非常全面的,只是有些Demo的後台是用PHP寫的,因此,如果想看更加全面的Demo的話,最好將幫組文檔發布到本地的Apache伺服器上。
2.用一個Demo來示範Jquery zTree的功能
要點:
2.1 zTree樹的資料來源為JSON格式
2.2 zTree樹控制項的資訊是通過請求url動態載入的
2.3 zTree樹的onClick函數,點擊樹的任意一個節點後,就會調用
3.Demo示範
3.1 頁面配置
為了能較為全面的示範zTree樹的功能,布局大致如下,左邊是樹行結構,右邊是首頁面。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE html><html><head><title>Jquery zTree</title><link rel="stylesheet" type="text/css" href="css/easyui.css"> <link rel="stylesheet" type="text/css" href="css/icon.css" /> <link rel="stylesheet" type="text/css" href="css/main.css" /><link rel="stylesheet" type="text/css" href="zTree/css/zTreeStyle/zTreeStyle.css"/><link rel="stylesheet" type="text/css" href="zTree/css/demo.css"/><script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.easyui.min.js"></script> <script type="text/javascript" src="zTree/js/jquery.ztree.all-3.5.js"></script><script type="text/javascript" src="js/index.js"></script></head><body id="main" class="easyui-layout"><div data-options="region:'west',split:true" title="Jquery zTree示範" style="width: 180px; overflow: auto; "><div class="easyui-accordion" data-options="fit:true,border:false"><div style="z-index:12754; border: 1px solid lightgray; background: white; width: 150px; height: 35px; display: none; padding: 4px;" id="treeLoadMsg"><img src="images/loading.gif" style="vertical-align: middle;" width="32" height="32"/><span>Loading...</span></div> <ul id="treeDemo" class="ztree"></ul></div></div><div data-options="region:'center'" title="main" style="overflow: hidden;"><iframe id="iframepage" src="default.jsp" style=" background: white;border: 1px; width: 100%; height: 100%; padding: 0;"></iframe></div></body></html>
為了不汙染原有的靜態頁面,我們將index.jsp檔案封裝在index.js檔案中,代碼如下:(注意注釋)
/** * 設定zTree樹 */var setting = {async: {enable: true,url: getUrlByNodeId},check: {enable: false},data: {simpleData: {enable: true}},view: {expandSpeed: ""},callback: {beforeExpand: beforeExpand,onAsyncSuccess: onAsyncSuccess,onAsyncError: onAsyncError,onClick: zTreeOnClick}};var zNodes =[{name:"經典視頻檢索", id:"1",isParent:true,iconOpen:"zTree/css/zTreeStyle/img/diy/1_open.png", iconClose:"zTree/css/zTreeStyle/img/diy/1_close.png"},{name:"基於內容檢索", id:"2",isParent:true,iconOpen:"zTree/css/zTreeStyle/img/diy/1_open.png", iconClose:"zTree/css/zTreeStyle/img/diy/1_close.png"},{name:"基於語義檢索", id:"3",isParent:true,iconOpen:"zTree/css/zTreeStyle/img/diy/1_open.png", iconClose:"zTree/css/zTreeStyle/img/diy/1_close.png"}];/** * @author ZhengHaibo * 功能:通過NodeId獲得節點的孩子節點 * 調用:當父節點展開時,調用,返回該父節點的子節點 * 後台資料格式:JSON * @param treeId 樹控制項的Id * @param treeNode 樹節點對象:包含Id等資訊 * @return */function getUrlByNodeId(treeId, treeNode) {return "getNodesDataById?treeNodeId="+treeNode.id;}/** * 展開之前執行的函數 * @param treeId * @param treeNode * @return */function beforeExpand(treeId, treeNode) {if (!treeNode.isAjaxing) {ajaxGetNodes(treeNode, "refresh");return true;} else {alert("Loading...");return false;}}/** * 載入成功後執行的函數 * @param event 封裝了js的事件 * @param treeId 樹控制項的Id * @param treeNode 樹節點對象 * @param msg 返回的JSON格式的訊息 * @return */function onAsyncSuccess(event, treeId, treeNode, msg) { console.log("treeId"); console.log(treeId); console.log("treeNode"); console.log(treeNode); console.log("msg"); console.log(msg);if (!msg || msg.length == 0) {return;}var zTree = $.fn.zTree.getZTreeObj("treeDemo");treeNode.icon = "";zTree.updateNode(treeNode);//更新樹結構zTree.selectNode(treeNode.children[0]);//設定為第一個子節點為選中狀態}function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {var zTree = $.fn.zTree.getZTreeObj("treeDemo");alert("Error ! 非同步擷取資料異常");treeNode.icon = "";zTree.updateNode(treeNode);}function ajaxGetNodes(treeNode, reloadType) {var zTree = $.fn.zTree.getZTreeObj("treeDemo");if (reloadType == "refresh") {treeNode.icon = "zTree/css/zTreeStyle/img/loading.gif";zTree.updateNode(treeNode);}zTree.reAsyncChildNodes(treeNode, reloadType, true);}/** * 功能:當點擊樹節點時,調用該函數 * @param event * @param treeId * @param treeNode * @return */function zTreeOnClick(event, treeId, treeNode) { console.log("zTreeOnClickLog:--------------------------------") console.log(treeId); console.log(treeNode); console.log(treeNode.id); switch(treeNode.id+""){//根據樹節點的Id判斷 case "1": case "11": document.getElementById("iframepage").src="tree_click_page.jsp?treeNodeId="+treeNode.id; break; case "12": document.getElementById("iframepage").src="tree_click_page.jsp?treeNodeId="+treeNode.id; break; case "13": document.getElementById("iframepage").src="tree_click_page.jsp?treeNodeId="+treeNode.id; break; case "2": case "21": document.getElementById("iframepage").src="tree_click_page.jsp?treeNodeId="+treeNode.id; break; case "22": document.getElementById("iframepage").src="tree_click_page.jsp?treeNodeId="+treeNode.id; break; case "23": document.getElementById("iframepage").src="tree_click_page.jsp?treeNodeId="+treeNode.id; break; case "24": document.getElementById("iframepage").src="tree_click_page.jsp?treeNodeId="+treeNode.id; break; case "3": case "31": document.getElementById("iframepage").src="tree_click_page.jsp?treeNodeId="+treeNode.id; break; }}$(document).ready(function(){$.fn.zTree.init($("#treeDemo"), setting, zNodes);//初始化zTree樹});
3.2後台
後台用的是Struts2架構,在struts.xml檔案中設定好Action,根據前台節點的不同id號返回不同JSON格式的資料
/* * $filename: ZTreeDemoAction.java,v $ * $Date: Sep 27, 2013 $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */package edu.njupt.zhb.ztree.action;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;/* *@author: ZhengHaibo *web: http://blog.csdn.net/nuptboyzhb *mail: zhb931706659@126.com *Sep 27, 2013 Nanjing,njupt,China */public class ZTreeDemoAction extends ActionSupport{/** * */private static final long serialVersionUID = -3318989776253565435L; private int treeNodeId;//儲存樹節點的Id/** * 返回樹的根節點的Json格式資料 * @return */public String getNodesDataById(){System.out.println("treeNodeId = "+treeNodeId);String iconPath = ",icon:\"zTree/css/zTreeStyle/img/diy/3.png\"";String icon2Path = ",icon:\"zTree/css/zTreeStyle/img/diy/2.png\"";String icon9Path = ",icon:\"zTree/css/zTreeStyle/img/diy/9.png\"";String lookIconPath = ",icon:\"zTree/css/zTreeStyle/img/diy/8.png\"";String nodesJson = "";if (treeNodeId == 1) {nodesJson = "[{id:11, pId:"+treeNodeId+", name: \"綜合檢索\",isParent:false"+iconPath+"}," + "{id:12, pId:"+treeNodeId+", name: \"視頻時間\",isParent:false"+iconPath+"}," + "{id:13, pId:"+treeNodeId+", name: \"視頻地點\",isParent:false"+iconPath+"}" + "]";}else if(treeNodeId == 2) {nodesJson = "[{id:21, pId:"+treeNodeId+", name: \"產生索引\",isParent:false"+icon2Path+"}," + "{id:22, pId:"+treeNodeId+", name: \"上傳映像\",isParent:false"+iconPath+"}," + "{id:23, pId:"+treeNodeId+", name: \"映像URL\",isParent:false"+iconPath+"}," + "{id:24, pId:"+treeNodeId+", name: \"查看索引\",isParent:false"+lookIconPath+"}" + "]";}else if (treeNodeId == 3) {nodesJson = "[{id:31, pId:"+treeNodeId+", name: \"語義檢索\",isParent:false"+icon9Path+"}]";}else{nodesJson = "[]";//其他情況:父節點沒有子節點}getPrintWriter().write(nodesJson);return SUCCESS;}/** * 獲得HttpServletResponse對象 * @return */public static HttpServletResponse getResponse() {HttpServletResponse response = ServletActionContext.getResponse();response.setContentType("text/html;charset=UTF-8");return response;}public PrintWriter getPrintWriter() {PrintWriter pw = null;try {pw = getResponse().getWriter();} catch (IOException e) {e.printStackTrace();}return pw;}public int getTreeNodeId() {return treeNodeId;}public void setTreeNodeId(int treeNodeId) {this.treeNodeId = treeNodeId;}}
4.頁面效果