jQuery easyUI樹形表格(TreeGrid)的簡單實現
網上只寫了頁面中實現的效果,數據固定,數據是json文件解決。下面我寫了一個從後臺模擬數據,在頁面顯示的效果demo,不足之處望指正!!!
效果圖如下:只截取了部分
頁面HTML標籤:
<table id="tt"></table>
頁面js代碼:
$('#tt').treegrid({
url:'${ctx }/account/treegrid.do',
title: 'TreeGrid',
iconCls: 'icon-save',
singleSelect:true,
idField:'id', //關鍵字段來標識樹節點,不能重複
treeField:'name', //樹節點字段,也就是樹節點的名稱
fitColumns:true,
rownumbers:true,//顯示一個行號列
collapsible:true,//收起表格的內容
width: 700,
height: 450,
loadMsg: '數據加載中...',
animate:true,//在節點展開或摺疊的時候是否顯示動畫效果
lines:true,//顯示treegrid行
columns:[[
{field:'name',title:'第一列',width:100,align:'left'},
{field:'size',title:'第二列',width:60,align:'center'},
{field:'date',title:'第三列',width:80,align:'center'}
]],
onLoadSuccess:function(data){
$('#tt').treegrid('expandAll');//全部展開樹節點
}
});
後臺代碼,模擬一些數據;數據格式:[{“id”:1,”name”:154,”children”:[{“id”:2,”name”:155}]}],children代表子節點中的數據,id是唯一的,否則easyUI解析的時候會出現錯誤。”state”:”closed”,數據中如果有這個屬性的值就代表子節點是摺疊的,效果如下:
其他節點展開,它及其它的子節點是摺疊的效果。
public static int j = 0;//成員變量,創建唯一的id值
@RequestMapping("/treegrid.do")
@ResponseBody
public DataGrid treeGrid() throws Exception{
j=0;
//所有的數據集合
List<Map<String, Object>> results = new ArrayList<Map<String,Object>>();
DataGrid dg = new DataGrid();
//模擬的幾條數據
results = createTreeGridChildren(14);
//返回到頁面的數據集合
dg.setRows(results);
dg.setTotal(j+1);
return dg;
}
/**
* 遞歸設置樹
* @param list
* @param id
* @return
*/
//n代表樹結構層數
private static List<Map<String, Object>> createTreeGridChildren(int n) {
List<Map<String, Object>> childList = new ArrayList<Map<String, Object>>();
Map<String, Object> map = null;
if(n==1){
map = new HashMap<String, Object>();
//在頁面easyUI插件treeGrid提供了數據轉換的columns屬性,具體看相關的js代碼
map.put("id", j+1);
map.put("size", j+1);
map.put("name", "歷史");
map.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
if (map != null)
childList.add(map);
return childList;
}else{
j++;
map = new HashMap<String, Object>();
map.put("id", j);
map.put("size", j);
map.put("name", "張三");
map.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
map.put("children", createTreeGridChildren(n-1));
childList.add(map);
return childList;
}
}
DataGrid 實體類,提供一些get,set方法。用到的屬性是結果集:rows,總記錄數:total
package util;
import java.util.List;
import java.util.Map;
public class DataGrid {
private int page = 1 ;// 當前頁
private List<Map<String,Object>> rows;// 結果集
private int pageSize = 10;//每頁顯示的數據的條數
private int total;// 總記錄數
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public List<Map<String, Object>> getRows() {
return rows;
}
public void setRows(List<Map<String, Object>> rows) {
this.rows = rows;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}