利用ztree js插件,產生一個異步的文件目錄樹

ztree這個js插件大家可以網上參考。這裏不多講:只將例子;

1.treeNode的model類

/**
 * @FILE:TreeNode.java
 * @AUTHOR:yehui
 * @DATE:2013-3-21 上午10:23:58
 **/
package jp.co.tsh.model;

import jp.co.tsh.common.BaseModel;

/*******************************************
 * @CLASS:TreeNode
 * @DESCRIPTION:treenode的model
 * @AUTHOR:yehui
 * @VERSION:v1.0
 * @DATE:2013-3-21 午前10:23:58
 *******************************************/
public class TreeNode extends BaseModel {

	/**
	 * id
	 */
	private String id;
	/**
	 * pid,父節點的id
	 */
	private String pid;
	/**
	 * 是否展開
	 */
	private boolean open;
	/**
	 * 是否有子節點
	 */
	private boolean isParent;
	/**
	 * 節點名稱
	 */
	private String name;
	/**
	 * 點擊事情
	 */
	private String click;
	/**   
	 *   節點所指向的文件路徑
	 */   
	private String path;

	public TreeNode(String id, String pid, boolean open, boolean isParent,
			String name, String click, String path) {
		this.id = id;
		this.pid = pid;
		this.open = open;
		this.isParent = isParent;
		this.name = name;
		this.click = click;
		this.path = path;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getPid() {
		return pid;
	}

	public void setPid(String pid) {
		this.pid = pid;
	}

	public boolean isOpen() {
		return open;
	}

	public void setOpen(boolean open) {
		this.open = open;
	}

	public boolean isParent() {
		return isParent;
	}

	public void setParent(boolean isParent) {
		this.isParent = isParent;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getClick() {
		return click;
	}

	public void setClick(String click) {
		this.click = click;
	}

	@Override
	public String toString() {
		return super.toString();
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

}

2.產生目錄樹的節點工具

/**
 * @FILE:BuildTreeUtils.java
 * @AUTHOR:yehui
 * @DATE:2013-3-21 下午7:23:12
 **/
package jp.co.tsh.common;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import jp.co.tsh.model.TreeNode;

/*******************************************
 * @CLASS:BuildTreeUtils
 * @DESCRIPTION: 產生目錄樹的節點工具
 * @AUTHOR:yehui
 * @VERSION:v1.0
 * @DATE:2013-3-21 午後7:23:12
 *******************************************/
public class BuildTreeNodeUtils {
	/**   
	 *   文件列表的工具類
	 */   
	private FileListUtils fUtils;
	/**   
	 *   根結點
	 */   
	private TreeNode headNode;
	/**   
	 *   父節點
	 */   
	private TreeNode parentNode;
	/**   
	 *   文件列表
	 */   
	private List<File> fList;
	/**   
	 *   目錄列表
	 */   
	private List<File> fDlist;
	/**   
	 *  
	 */   
	private boolean flag;
	private String pid;
	/**   
	 *   是否有子節點
	 */   
	private boolean isParent;
	/**   
	 *  目錄樹的數據
	 */   
	private StringBuffer treeNodeData;
	/**   
	 *   文件路徑
	 */   
	private String path;

	public BuildTreeNodeUtils(String path) {
		this.path = path;
	}

	public BuildTreeNodeUtils(TreeNode tn, boolean flag) {
		if (tn != null) {
			fUtils = new FileListUtils(tn.getPath());
			fList = fUtils.getfList();
			fDlist = fUtils.getdList();
			this.flag = flag;
			this.pid = tn.getId();
			this.parentNode = tn;
		}
	}

	/**@description:構造一個根節點的json數據
	 * @author:yehui
	 * @return:StringBuffer
	 * @return*/
	
	public StringBuffer init() {
		getHeadNode();
		treeNodeData = new StringBuffer();
		// {id:1, pId:0, name:"[core] 基本的な操作の例", open:true},
		treeNodeData.append("[{id:").append(headNode.getId()).append(",pid:")
				.append(headNode.getPid()).append(",open:")
				.append(headNode.isOpen()).append(",isParent:")
				.append(headNode.isParent()).append(",name:\"")
				.append(headNode.getPath().replaceAll("\\\\", "/"))
				.append("\"").append(",click:\"").append(headNode.getClick()).
				append("\"").append(",path:\"").append(headNode.getPath().replaceAll("\\\\", "/")).append("\"").append("}]");
		return treeNodeData;
	}

	/**@description:獲得根節點
	 * @author:yehui
	 * @return:TreeNode
	 * @return*/
	
	public TreeNode getHeadNode() {
		
		File ftemp = new File(path);
		if (ftemp.isDirectory() && ftemp.listFiles().length > 0) {
			headNode = new TreeNode("0", "0", false, true, ftemp.getPath(),
					"getChildNodes",ftemp.getPath());
		} else {
			headNode = new TreeNode("0", "0", false, false, ftemp.getPath(),
					"getChildNodes",ftemp.getPath());
		}

		return headNode;
	}

	/**@description:	獲得某個節點的子節點
	 * @author:yehui
	 * @return:List<TreeNode>
	 * @return*/
	
	public List<TreeNode> findChildNodes() {
		List<TreeNode> ltList = null;
		if (parentNode.isParent()) {
			ltList = new ArrayList<TreeNode>();
			if (flag) {
				for (int i = 0; i < fList.size(); i++) {
					File file = new File(fList.get(i).getPath());
					if (file.exists()) {
						if (file.isDirectory()) {
							isParent = true;
						} else {
							isParent = false;
						}
					}
					TreeNode tNode;
					if (isParent) {
						tNode = new TreeNode(pid + i, pid, false, true, fList
								.get(i).getName(), "getChildNodes();",fList
								.get(i).getPath());
					} else {
						tNode = new TreeNode(pid + i, pid, false, false, fList
								.get(i).getName(), "",fList
								.get(i).getPath());
					}
					ltList.add(tNode);
				}
			} else {
				for (int i = 0; i < fDlist.size(); i++) {
					TreeNode tNode;
					tNode = new TreeNode(pid + i, pid, false, true, fDlist
							.get(i).getName(), "",fDlist
							.get(i).getPath());
					ltList.add(tNode);
				}
			}
		}
		return ltList;
	}

	/**@description:	構造子節點的json數據
	 * @author:yehui
	 * @return:StringBuffer
	 * @return*/
	
	public StringBuffer getTreeNodeData() {
		List<TreeNode> ltList = findChildNodes();
		int count = ltList.size();
		if (count > 0) {
			treeNodeData = new StringBuffer();
			treeNodeData.append("[");
			for (int i = 0; i < count; i++) {
				TreeNode tempNode = ltList.get(i);
				treeNodeData.append("{id:").append(tempNode.getId())
						.append(",pid:").append(tempNode.getPid())
						.append(",open:").append(tempNode.isOpen())
						.append(",isParent:").append(tempNode.isParent())
						.append(",name:").append("\"")
						.append(tempNode.getName().replaceAll("\\\\", "/"))
						.append("\"").append(",click:\"")
						.append(tempNode.getClick()).append("\"").append(",path:").append("\"").append(tempNode.getPath().replaceAll("\\\\", "/")).append("\"").append("}");
				if (i == count - 1) {
					treeNodeData.append("]");
				} else {
					treeNodeData.append(",");
				}
			}
		}
		return treeNodeData;
	}

	public TreeNode stringToTreeNode(String str) {

		TreeNode tmpNode;
		return null;
	}

	public String getFileName() {
		return parentNode.getName();
	}

	public FileListUtils getfUtils() {
		return fUtils;
	}

	public TreeNode getParentNode() {
		return parentNode;
	}

	public List<File> getfList() {
		return fList;
	}

	public List<File> getfDlist() {
		return fDlist;
	}

	public boolean isFlag() {
		return flag;
	}

	public String getPid() {
		return pid;
	}

	public boolean isParent() {
		return isParent;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}
}
jsp頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>

<%--<jsp:include page="./views/common/secondHeader.jsp"></jsp:include>--%>
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=8" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="${ctx}/CSS/zTreeStyle/zTreeStyle.css"
	type="text/css">
<script type="text/javascript"
	src="${ctx}/scripts/jquery.ztree.core-3.5.js"></script>
<SCRIPT type="text/javascript">//這裏可以設置你需要出發的事件
	var setting = {
		view : {
			dblClickExpand : false,
			showLine : false
		},
		data : {
			simpleData : {
				enable : true
			}
		},
		callback : {
			beforeExpand: beforeExpand,
			onClick : onClick
		}
	};//從後臺獲得的節點數據
	var zNodes = ${treeNodeData.toString()};//點擊事件的處理
	function beforeClick(treeId, treeNode) {
		var check = (treeNode && treeNode.isParent);
		var fileSelect = $("#fileSel");
		fileSelect.attr("value", treeNode.path);
		return check;
	}
//onclick事件的處理過程
	function onClick(e, treeId, treeNode) {
		var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
			treeObj.expandAll(false);
		}
		var zTree = $.fn.zTree.getZTreeObj("treeDemo"), nodes = zTree
				.getSelectedNodes(), v = "";
		nodes.sort(function compare(a, b) {
			return a.id - b.id;
		});
		for ( var i = 0, l = nodes.length; i < l; i++) {
			v += nodes[i].path + ",";
		}
		if (v.length > 0)
			v = v.substring(0, v.length - 1);
		var fileSelect = $("#fileSel");
		fileSelect.attr("value", v);
	}

	function showMenu() {
		var cityObj = $("#fileSel");
		var cityOffset = $("#fileSel").offset();
		$("#menuContent").css({
			left : cityOffset.left + "px",
			top : cityOffset.top + cityObj.outerHeight() + "px",
			bottom:cityOffset.top+100+"px"
		}).slideDown("fast");

		$("body").bind("mousedown", onBodyDown);
	}
	function hideMenu() {
		$("#menuContent").fadeOut("fast");
		$("body").unbind("mousedown", onBodyDown);
	}
	function onBodyDown(event) {
		if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(
				event.target).parents("#menuContent").length > 0)) {
			hideMenu();
		}
	}
	function beforeExpand(treeId, treeNode) {
		getChildNodes(treeNode);
	}
	$(document).ready(function() {
		$.fn.zTree.init($("#treeDemo"), setting, zNodes);
	});
</SCRIPT>
<script type="text/javascript">//這裏做一個點擊節點後,異步加載子節點的js
	function getChildNodes(treeNode) {
		if(treeNode!=null){
		var id;
		var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
<%--		var nodes = treeObj.getSelectedNodes();--%>
		id = treeNode.id;
		var name = treeNode.name;
		var pid = treeNode.pid;
		var open = treeNode.open;
		var isParent = treeNode.isParent;
		var click = treeNode.click;
		var path = treeNode.path;
		var node = treeObj.getNodesByFilter(function() {
			return true;
		}, true, treeNode, "");

		if (node == null) {
			var url=$("#url").val();
			var flag=$("#flag").val();
			$.post(url, {
				name : name,
				flag : flag,
				id : id,
				pid : pid,
				open : open,
				isParent : isParent,
				click : click,
				path:path
			}, function(data) {//先移除所有的節點,後加載
				treeObj.removeChildNodes(treeNode);
				treeObj.addNodes(treeNode, data.info)
			}, 'json')
		} 
		}
	}
</script>
</HEAD>

<BODY >
<div class="content_wrap" >
		<div class="zTreeDemoBackground left" >
<%--<span>參照先:</span>--%>  //點擊樹的節點後,會將節點所對應的文件path放在fileSel這個input標籤中。
		<span><input id="fileSel" name="fileSel" type="text" οnclick="showMenu(); return false;"  readonly value="" /></span>
		</div>
	</div>
       //加載目錄樹
	<div  id="menuContent" class="menuContent"
		style="display:none; position: absolute; background-color: #FFFFFF;height:auto" >
		<ul id="treeDemo" class="ztree" style="margin-top:0; width:160px;height:auto"></ul>
	</div>
	
</BODY>
</HTML>
至於css可以直接使用ztree提供的css文件,點擊打開鏈接查看對css的詳細解釋。



發佈了38 篇原創文章 · 獲贊 10 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章