初试easyui,功能挺强大,但是研究了一下,逐渐攻克easyui的各个模块,今天主要是关于easyui tree的一些使用主要包括四方面,初始化加载tree(当然这里使用初始化tree数据并不是页面生成的,而是通过后台取出来的数据组装成的json tree,然后生成树),添加子节点,修改子节点,删除子节点,以及叶子节点加载tab,根据数据库数据来生成图表趋势图。
1. Tree的初始化
由页面静态加载的,大家都知道了,easyui API也有,我就不再赘述了,这里主要是怎么通过ajax后台请求数据,并生成tree。
我们一般都是会配合一个登录系统来实现,用户登录之后会出现tree的页面,在页面初始化的时候加载tree,就需要onload时间来实现,或者使用jQuery的$(function (){});也能实现。
代码如下:
$(function () {
// 登录成功提示
$.messager.show({
title : '提示',
msg : "登录成功"
});
// 一下添加tree代码
});
这样当页面元素加载完成就会调用function,这时在里面加上tree的加载就行。
// 实例化树菜单
$("#tree").tree({
url:'getNodesById.do?id=1',// 请求路径
onLoadSuccess:function(node,data){// 成功加载树之后的操作
var tree = $(this);
if(data){
$(data).each(function(index,d) {// 遍历生成节点
if (this.state=='closed') {
tree.tree('expandAll');
}
});
}
}
});
上面的代码就是简单的加载tree的方法,其中url就是请求路径,在这里会根据url去同后台进行交互,后台只要组装好数据,response后前天就行。
/**
* 初始化所有的树形节点
* @throws UnsupportedEncodingException
*/
@RequestMapping(value="/getNodesById")
public void getNodesById(@RequestParam int id ,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
System.out.println("kaishi");
String str ="";
StringBuilder json = new StringBuilder();
// 获得根节点
Tree treeRoot = treeService.getNodeById(id);
// 拼接根节点
json.append("[");
json.append("{\"id\":" +String.valueOf(treeRoot.getId()));
json.append(",\"text\":\"" +treeRoot.getText() + "\"");
json.append(",\"state\":\"open\"");
// 获取根节点下的所有子节点
List<Tree> treeList = treeService.getNodesById(id);
// 遍历子节点下的子节点
if(treeList!=null && treeList.size()!=0){
json.append(",\"children\":[");
for (Tree t : treeList) {
json.append("{\"id\":" +String.valueOf(t.getId()));
json.append(",\"text\":\"" +t.getText() + "\"");
json.append(",\"state\":\"open\"");
// 该节点有子节点
// 设置为关闭状态,而从构造异步加载tree
List<Tree> tList = treeService.getNodesById(t.getId());
if(tList!=null && tList.size()!=0){// 存在子节点
json.append(",\"children\":[");
json.append(dealJsonFormat(tList));// 存在子节点的都放在一个工具类里面处理了
json.append("]");
}
json.append("},");
}
str = json.toString();
str = str.substring(0, str.length()-1);
str+="]}]";
}
try {
System.out.println("输出json数据"+str);
response.getWriter().print(str);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 处理数据集合,将数据集合转为符合格式的json
* @param tList 参数
* @return json字符串
*/
public String dealJsonFormat(List<Tree> tList){
StringBuilder json = new StringBuilder();
for (Tree tree : tList) {
json.append("{\"id\":" +String.valueOf(tree.getId()));
json.append(",\"text\":\"" +tree.getText() + "\"");
json.append(",\"attributes\":\""+tree.getAttributes()+"\"");
json.append("},");
}
String str = json.toString();
str = str.substring(0, str.length()-1);
System.out.println("---------"+str);
return str;
}
// 输出的json格式
[
{
"id": 1,
"text": "功能菜单",
"state": "open",
"children": [
{
"id": 2,
"text": "北京",
"state": "open",
"children": [
{
"id": 4,
"text": "北京IOP数据",
"attributes": "showAreaList.do?"
},
{
"id": 5,
"text": "北京虚拟机数据",
"attributes": "showAreaList.do?"
}
]
},
{
"id": 3,
"text": "上海",
"state": "open",
"children": [
{
"id": 6,
"text": "上海IOP数据",
"attributes": "showAreaList.do?"
},
{
"id": 7,
"text": "上海虚拟机数据",
"attributes": "showAreaList.do?"
}
]
}
]
}
]
上面就是输出的json格式,这样返回到前端就可以生成tree了。
2. 节点的增删改
这个我没有研究出来直接在添加修改时,焦点聚焦到选中的节点,使用了另外一种方法,使用easyui的dialog弹出窗来实现的,这个不要见笑了。
这样实现,就能轻易的获取节点的内容了,之后就是提交事件触发ajax请求后台数据了。
(1) 右键菜单功能
就是简单的创建一个div,这个菜单引入easyui的样式就行。这里定义id是为了方便判断选中的是添加,修改,删除中的哪一个。
html:
<div id="tabsMenu" class="easyui-menu" style="width:120px;">
<div name="close" id="1">添加</div>
<div name="Other" id="2">修改</div>
<div name="All" id="3">删除</div>
</div>
千万别再这里面创建onclick事件,tree里面已经提供了现成的方法。
// 实例化树菜单
$("#tree").tree({
url:'getNodesById.do?id=1',
onLoadSuccess:function(node,data){// 加载树
var tree = $(this);
if(data){
$(data).each(function(index,d) {
if (this.state=='closed') {
tree.tree('expandAll');
}
});
}
}
onContextMenu: function(e,node){// 生成右键菜单
e.preventDefault();
$(this).tree('select',node.target);
$('#tabsMenu').menu('show',{
left: e.pageX,
top: e.pageY
});
$('#tabsMenu').menu({
onClick:function(item){ // 根据选择的id判断选中的是添加,修改,还是删除
if(item.id==1){// 添加
document.getElementById("mydialog").title = "添加节点";
var node = $("#tree").tree('getSelected');
document.getElementById("txRolename").value = "";
alert(node.text);
$('#mydialog').show(); // 弹出框显示
$('#mydialog').dialog({
collapsible: true,
minimizable: true,
maximizable: true,
buttons: [{
text: '提交',
iconCls: 'icon-ok',
handler: function() {
$.ajax({
url : "addTreeNode.do",
type : "post",
async : false,
data : "area="+$("#txRolename").val()+"&pid="+node.id,
dataType:"json",
success : function(data) {
loadTree();
$('#mydialog').dialog('close');
}
});
}
}, {
text: '取消',
handler: function() {
$('#mydialog').dialog('close');
}
}]
});
}else if(item.id==2){// 修改
var node = $("#tree").tree('getSelected');
document.getElementById("mydialog").title = "修改节点";
document.getElementById("txRolename").value = node.text;
$('#mydialog').show();
$('#mydialog').dialog({
collapsible: true,
minimizable: true,
maximizable: true,
buttons: [{
text: '提交',
iconCls: 'icon-ok',
handler: function() {
$.ajax({
url : "updTreeNode.do",
type : "post",
async : false,
data : "area="+$("#txRolename").val()+"&id="+node.id,
dataType:"json",
success : function(data) {
loadTree();
$('#mydialog').dialog('close');
}
});
}
}, {
text: '取消',
handler: function() {
$('#mydialog').dialog('close');
}
}]
});
}else if(item.id==3){// 删除
var node = $("#tree").tree('getSelected');
$('#mydialogtemp').show();
$('#mydialogtemp').dialog({
collapsible: true,
minimizable: true,
maximizable: true,
buttons: [{
text: '提交',
iconCls: 'icon-ok',
handler: function() {
alert('提交数据');
$.ajax({
url : "delTreeNode.do",
type : "post",
async : false,
data :"id="+node.id,
dataType:"json",
success : function(data) {
loadTree();
$('#mydialogtemp').dialog('close');
}
});
}
}, {
text: '取消',
handler: function() {
$('#mydialog').dialog('close');
}
}]
});
}
}
});
}
});
这样就可以实现右键功能了,我这里顺便把增删改写上了。这点简单相信大家都能看懂,接下来的事情就是与后台交互了,这里就不在赘述了。添加,修改,删除之后,别忘记重新加载一下树。
// 加载树
function loadTree(){
$("#tree").tree({
url:'getNodesById.do?id=1',
onLoadSuccess:function(node,data){
var tree = $(this);
if(data){
$(data).each(function(index,d) {
if (this.state=='closed') {
tree.tree('expandAll');
}
});
}
}});
}
3. 叶子节点点击事件
主要是使用ifream来加载一个新的页面
// 实例化树菜单
$("#tree").tree({
url:'getNodesById.do?id=1',
onLoadSuccess:function(node,data){// 加载树
var tree = $(this);
if(data){
$(data).each(function(index,d) {
if (this.state=='closed') {
tree.tree('expandAll');
}
});
}
},
onClick:function(node){// 添加tab
if(node.attributes){
node1=$("#tree").tree('getParent',node.target);
openTab(node.text,node.attributes,node1.text);
}
}
});
// 新增Tab
function openTab(text,url,text1){
if($("#tabs").tabs('exists',text)){
$("#tabs").tabs('select',text);
}else{
url = url+"area="+text1;
alert(url);
var content="<iframe frameborder='0' scrolling='auto' style='width:100%;height:100%' src="+url+"></iframe>";
$("#tabs").tabs('add',{
title:text,
closable:true,
content:content
});
}
}
});
然后后台代码指向新页面,这样就会加载进去了。昨天由于比较忙,就没有上全部的代码,今天把代码补上,这个树的生成及操作。
前端HTML代码
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
%>
<!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=utf-8" />
<script src="js/jquery-easyui-1.4.1/jquery.min.js"></script>
<script src="js/jquery-easyui-1.4.1/jquery.easyui.min.js"></script>
<link href="js/jquery-easyui-1.4.1/themes/default/easyui.css" rel="stylesheet"/>
<link href="js/jquery-easyui-1.4.1/themes/icon.css" rel="stylesheet" />
<script src="js/jquery-easyui-1.4.1/locale/easyui-lang-zh_CN.js"></script>
<script >
var node1;
$(function () {
// 登录成功提示
$.messager.show({
title : '提示',
msg : "登录成功"
});
// 实例化树菜单
$("#tree").tree({
url:'getNodesById.do?id=1',
onLoadSuccess:function(node,data){// 加载树
var tree = $(this);
if(data){
$(data).each(function(index,d) {
if (this.state=='closed') {
tree.tree('expandAll');
}
});
}
},
onClick:function(node){// 添加tab
if(node.attributes){
node1=$("#tree").tree('getParent',node.target);
openTab(node.text,node.attributes,node1.text);
}
},
onContextMenu: function(e,node){// 生成右键菜单
e.preventDefault();
$(this).tree('select',node.target);
$('#tabsMenu').menu('show',{
left: e.pageX,
top: e.pageY
});
$('#tabsMenu').menu({
onClick:function(item){
if(item.id==1){// 添加
document.getElementById("mydialog").title = "添加节点";
var node = $("#tree").tree('getSelected');
document.getElementById("txRolename").value = "";
alert(node.text);
$('#mydialog').show();
$('#mydialog').dialog({
collapsible: true,
minimizable: true,
maximizable: true,
buttons: [{
text: '提交',
iconCls: 'icon-ok',
handler: function() {
$.ajax({
url : "addTreeNode.do",
type : "post",
async : false,
data : "area="+$("#txRolename").val()+"&pid="+node.id,
dataType:"json",
success : function(data) {
loadTree();
$('#mydialog').dialog('close');
}
});
}
}, {
text: '取消',
handler: function() {
$('#mydialog').dialog('close');
}
}]
});
}else if(item.id==2){// 修改
var node = $("#tree").tree('getSelected');
document.getElementById("mydialog").title = "修改节点";
document.getElementById("txRolename").value = node.text;
$('#mydialog').show();
$('#mydialog').dialog({
collapsible: true,
minimizable: true,
maximizable: true,
buttons: [{
text: '提交',
iconCls: 'icon-ok',
handler: function() {
$.ajax({
url : "updTreeNode.do",
type : "post",
async : false,
data : "area="+$("#txRolename").val()+"&id="+node.id,
dataType:"json",
success : function(data) {
loadTree();
$('#mydialog').dialog('close');
}
});
}
}, {
text: '取消',
handler: function() {
$('#mydialog').dialog('close');
}
}]
});
}else if(item.id==3){// 删除
var node = $("#tree").tree('getSelected');
$('#mydialogtemp').show();
$('#mydialogtemp').dialog({
collapsible: true,
minimizable: true,
maximizable: true,
buttons: [{
text: '提交',
iconCls: 'icon-ok',
handler: function() {
alert('提交数据');
$.ajax({
url : "delTreeNode.do",
type : "post",
async : false,
data :"id="+node.id,
dataType:"json",
success : function(data) {
loadTree();
$('#mydialogtemp').dialog('close');
}
});
}
}, {
text: '取消',
handler: function() {
$('#mydialog').dialog('close');
}
}]
});
}
}
});
}
});
// 加载树
function loadTree(){
$("#tree").tree({
url:'getNodesById.do?id=1',
onLoadSuccess:function(node,data){
var tree = $(this);
if(data){
$(data).each(function(index,d) {
if (this.state=='closed') {
tree.tree('expandAll');
}
});
}
}});
}
// 新增Tab
function openTab(text,url,text1){
if($("#tabs").tabs('exists',text)){
$("#tabs").tabs('select',text);
}else{
url = url+"area="+text1;
alert(url);
var content="<iframe frameborder='0' scrolling='auto' style='width:100%;height:100%' src="+url+"></iframe>";
$("#tabs").tabs('add',{
title:text,
closable:true,
content:content
});
}
}
});
// 注销系统
function getOut(){
window.location.href ="<%=path%>/getOut.do";
}
</script>
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
.west{
width:200px;
padding:10px;
}
.north{
height:75px;
}
.south{
height:50px;
}
</style>
</head>
<body class="easyui-layout">
<div region="north" class="north" style="background:url('image/autelan.png') no-repeat;">
<div style="float:right;font-size: 15px;height:60px;text-align: center;padding-right: 20px;padding-bottom: 10px;">
欢迎<span style="color:red">${sessionScope.user.username}</span>登陆
<a href="#" οnclick="getOut()">
<img src="image/exit.png"/>注销</a>
<a href="javascript:history.go(-1);">
<img src="image/nav_back.gif" />后退</a>
<a href="javascript:history.go(1);">
<img src="image/nav_forward.gif" />前进
</a>
</div>
</div>
<div region="center" title="数据管理">
<div class="easyui-tabs" fit="true" border="false" id="tabs">
</div>
</div>
<div region="west" class="west" title="导航菜单">
<ul id="tree"></ul>
</div>
<div region="south" class="south" style="text-align: center">
版权所有@-----------------------翻版必究
</div>
<div id="tabsMenu" class="easyui-menu" style="width:120px;">
<div name="close" id="1">添加</div>
<div name="Other" id="2">修改</div>
<div name="All" id="3">删除</div>
</div>
<div id="mydialog" style="display:none;padding:5px;width:400px;height:100px;">
<label class="lbInfo">节点名称:</label>
<input id="txRolename" type="text" class="easyui-validatebox" required="true" /><br />
</div>
<div id="mydialogtemp" style="display:none;padding:5px;width:400px;height:100px;" title="删除节点">
你确定要删除该节点?删除的同时会将该节点下的所有子节点删除!
</div>
</body>
</html>
后台Java代码
package com.chenqk.springmvc.controller;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.chenqk.springmvc.service.TreeService;
import com.chenqk.springmvc.entity.Tree;
/**
* 控制类
* @author chenqk
*
*/
@Controller
@RequestMapping("/")
public class TreeController{
@Autowired
@Qualifier("TreeService")
private TreeService treeService;
private static Logger logger = Logger.getLogger(TreeController.class);
/**
* 初始化所有的树形节点
* @throws UnsupportedEncodingException
*/
@RequestMapping(value="/getNodesById")
public void getNodesById(@RequestParam int id ,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
System.out.println("kaishi");
String str ="";
StringBuilder json = new StringBuilder();
// 获得根节点
Tree treeRoot = treeService.getNodeById(id);
// 拼接根节点
json.append("[");
json.append("{\"id\":" +String.valueOf(treeRoot.getId()));
json.append(",\"text\":\"" +treeRoot.getText() + "\"");
json.append(",\"state\":\"open\"");
// 获取根节点下的所有子节点
List<Tree> treeList = treeService.getNodesById(id);
// 遍历子节点下的子节点
if(treeList!=null && treeList.size()!=0){
json.append(",\"children\":[");
for (Tree t : treeList) {
json.append("{\"id\":" +String.valueOf(t.getId()));
json.append(",\"text\":\"" +t.getText() + "\"");
json.append(",\"state\":\"open\"");
// 该节点有子节点
// 设置为关闭状态,而从构造异步加载tree
List<Tree> tList = treeService.getNodesById(t.getId());
if(tList!=null && tList.size()!=0){// 存在子节点
json.append(",\"children\":[");
json.append(dealJsonFormat(tList));// 存在子节点的都放在一个工具类里面处理了
json.append("]");
}
json.append("},");
}
str = json.toString();
str = str.substring(0, str.length()-1);
str+="]}]";
}
try {
System.out.println("输出json数据"+str);
response.getWriter().print(str);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 添加新节点
* @param area 节点名称
* @param pid 父节点id
* @param request
* @param response
*/
@RequestMapping(value="/addTreeNode")
public void addTreeNode(@RequestParam String area,String pid,HttpServletRequest request,HttpServletResponse response){
System.out.println("area="+area+",pid="+pid);
Tree tree = new Tree();
tree.setPid(Integer.parseInt(pid));
tree.setText(area);
tree.setAttributes("showAreaList.do?");
treeService.addTreeNode(tree);
try {
this.getNodesById(1, request, response);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 修改节点名称
* @param area 节点名称
* @param id 节点id
* @param request
* @param response
*/
@RequestMapping(value="/updTreeNode")
public void updTreeNode(@RequestParam String area,String id,HttpServletRequest request,HttpServletResponse response){
Tree tree = new Tree();
tree.setId(Integer.parseInt(id));
tree.setText(area);
treeService.updTreeNode(tree);
try {
this.getNodesById(1, request, response);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 删除节点
* @param id 节点id
* @param pid
* @param request
* @param response
*/
@RequestMapping(value="/delTreeNode")
public void delTreeNode(@RequestParam String id,HttpServletRequest request,HttpServletResponse response){
treeService.delTreeNode(Integer.parseInt(id));
try {
this.getNodesById(1, request, response);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 处理数据集合,将数据集合转为符合格式的json
* @param tList 参数
* @return json字符串
*/
public String dealJsonFormat(List<Tree> tList){
StringBuilder json = new StringBuilder();
for (Tree tree : tList) {
json.append("{\"id\":" +String.valueOf(tree.getId()));
json.append(",\"text\":\"" +tree.getText() + "\"");
json.append(",\"attributes\":\""+tree.getAttributes()+"\"");
json.append("},");
}
String str = json.toString();
str = str.substring(0, str.length()-1);
System.out.println("---------"+str);
return str;
}
public TreeService getTreeService() {
return treeService;
}
public void setTreeService(TreeService treeService) {
this.treeService = treeService;
}
}
至此代码实现完成,项目已上传包括sql文件,使用的框架是easyui +mybatis +springmvc 想要学习的童鞋们,可以我的资源里面下载
http://download.csdn.net/detail/chenqk_123/8476853