当前位置: 代码迷 >> JavaScript >> 用javascript兑现的TreeTable, 可以当做树(Tree)用
  详细解决方案

用javascript兑现的TreeTable, 可以当做树(Tree)用

热度:434   发布时间:2012-11-23 00:03:43.0
用javascript实现的TreeTable, 可以当做树(Tree)用
本文版权归作者所有,仅供用来网上学习来用,读者可以收藏,请不要下载到本机和重新发布到其它网站

有觉得可以改进的,请留言,也可加群讨论71326533


近日,需要做一个关于Service的Mapping, 因为排版的需要,需要一个TreeTable,我们用的js框架是dojo,但是定制dojo(1.4)很困难,且我们这个tree table不需要太多的功能,所以最终决定自己实现一个,API类似于dojo的TreeGrid, 因为涉及版权问题,我采用了纯js的方法。目前这个tree table可以在firefox和IE6.0+上运行

看网上有几种tree table的实现,都是先把表格或数据填好,然后再对表格进行处理,但是很少有需求是这样,实际应用中,数据可能就是JSON对象,这个JSON对象有自己的结构。用户需要把这个JSON用TreeTable的形式展现出来。

这个TreeTable,如果只有一列的话,就是常用的Tree控件了

这是我写的TreeTable.js文件
var _treeTableIcons = {};
// 树结点是否有竖线,因为如果有竖线的话,行高过高,线就不能连在一起,很难看,最好像windows的资源管理器一样,不要添加结点之间的连线。默认也是不添加连线的
var showLine = false;
if (showLine) {
	_treeTableIcons['empty'] = 'images/empty.gif';
	_treeTableIcons['folder'] = 'images/folder.gif';
	_treeTableIcons['folderopen'] = 'images/folderopen.gif';
	_treeTableIcons['join'] = 'images/join.gif';
	_treeTableIcons['joinbottom'] = 'images/joinbottom.gif';
	_treeTableIcons['line'] = 'images/line.gif';
	_treeTableIcons['minus'] = 'images/minus.gif';
	_treeTableIcons['minusbottom'] = 'images/minusbottom.gif';
	_treeTableIcons['nolines_minus'] = 'images/nolines_minus.gif';
	_treeTableIcons['nolines_plus'] = 'images/nolines_plus.gif';
	_treeTableIcons['page'] = 'images/page.gif';
	_treeTableIcons['plus'] = 'images/plus.gif';
	_treeTableIcons['plusbottom'] = 'images/plusbottom.gif';
} else {
	_treeTableIcons['empty'] = 'images/empty.gif';
	_treeTableIcons['folder'] = 'images/folder.gif';
	_treeTableIcons['folderopen'] = 'images/folderopen.gif';
	_treeTableIcons['join'] = 'images/empty.gif';
	_treeTableIcons['joinbottom'] = 'images/empty.gif';
	_treeTableIcons['line'] = 'images/empty.gif';
	_treeTableIcons['minus'] = 'images/nolines_minus.gif';
	_treeTableIcons['minusbottom'] = 'images/nolines_minus.gif';
	_treeTableIcons['nolines_minus'] = 'images/nolines_minus.gif';
	_treeTableIcons['nolines_plus'] = 'images/nolines_plus.gif';
	_treeTableIcons['page'] = 'images/page.gif';
	_treeTableIcons['plus'] = 'images/nolines_plus.gif';
	_treeTableIcons['plusbottom'] = 'images/nolines_plus.gif';
}

function TreeTable(layout, model, divId, id) {
	this.divId = divId;
	this.mapping = {};
	this.model = model;
	this.layout = layout;
	this.addNode = _addNode;
	this.startup = _startup;
	this.setRoot = _setRoot;
	this.getRoot = _getRoot;
	this.expandNode = _expandNode;
	this.expandAll = _expandAll;
	TreeTable.prototype.instants[this.id = id ? id : TreeTable.prototype._treeIdPrefix + TreeTable.prototype.index++] = this;
}

function TreeNode(item) {
	this.item = item;
	this.nodes = [];
}

TreeTable.prototype._treeIdPrefix = 'treeTable_';
TreeTable.prototype.instants = {};
TreeTable.prototype.index = 0;
TreeNode.prototype.index = 0;

function _addNode(parentNode, childNode) {
	if (parentNode) {
		childNode.parentId = parentNode.id;
		childNode.id = parentNode.id + '_' + TreeNode.prototype.index++;
		parentNode.nodes[parentNode.nodes.length] = childNode;
		childNode.parent = parentNode;
	} else {
		childNode.id = this.id + '_' + TreeNode.prototype.index++;
	}
	childNode.isOpened = true;
	this.mapping[childNode.id]=childNode;
}

function _getRoot() {
	return this.rootNode;
}

function _setRoot(rootNode) {
	this.addNode(null, rootNode);
	this.rootNode = rootNode;
}

function _startup() {
	if (this.layout && this.layout.constructor == Array && this.layout.length > 0) {
		_makeupNodes(this);
		var tableHeaderStr = '<thead class="treeTableHeader"><tr>';
		for (var i = 0; i < layout.length; i++) {
			var headerClass = this.layout[i].headerClass ? ' class="' + this.layout[i].headerClass + '"' : '';
			tableHeaderStr += '<td' + headerClass + '>' + this.layout[i].name + '</td>';
		}
		tableHeaderStr += '</tr></thead>';
		var tableStr = '<table id="' + this.id + '" class="treeTable">' + tableHeaderStr + _makeupHTML(this, this.layout, this.getRoot(), this.getRoot(), -1, -1, '') + '</table>';
		document.getElementById(this.divId).innerHTML = tableStr;
	}
}

function _makeupNodes(treeTable) {
	var model = treeTable.model;
	var jsonStore = model.store;
	if (jsonStore) {
		var childrenAttrs = model.childrenAttrs;
		_traverseModel(treeTable, null, jsonStore, childrenAttrs);
	}
}

function _traverseModel(treeTable, parentNode, item, childrenAttrs) {
	if (item) {
		var treeNode = new TreeNode(item);
		treeTable.addNode(parentNode, treeNode);
		var children = item[childrenAttrs];
		if (children && children.constructor == Array) {
			for ( var i = 0; i < children.length; i++) {
				_traverseModel(treeTable, treeNode, children[i], childrenAttrs);
			}
		}
		if (!parentNode) {
			treeTable.setRoot(treeNode);
		}
	}
}

function _makeupHTML(treeTable, layout, rootNode, treeNode, index, count, indent) {
	var htmlStr = '';
	if (treeNode && treeNode.item) {
		var isFolderNode = (treeNode.nodes.length > 0);
		htmlStr = '<tr id="' + treeNode.id + '" class="treeTableRow">\n';
		for (var colIdx = 0; colIdx < layout.length; colIdx++) {
			var tdText = layout[colIdx].get ? layout[colIdx].get(treeNode.item, colIdx, treeNode, treeTable) : _get(treeNode.item, colIdx, treeNode, treeTable);
			var className = layout[colIdx].className;
			var style = layout[colIdx].style;
			var icon = layout[colIdx].getIcon ? layout[colIdx].getIcon(treeNode.item, colIdx, treeNode, true, treeTable) : _getIcon(treeNode.item, colIdx, treeNode, true, treeTable);
			var iconElement = '';
			if (icon && icon != '') {
				iconElement = '<img src="' + icon + '" style="vertical-align: middle" alt="" />';
			}
			if (colIdx == 0){
				var imageStr = '';
				var eventStr = '';
				if (isFolderNode) {
					eventStr = isFolderNode ? ' id="folder_' + treeNode.id + '" onclick="javascript:handleNodeClick(event)"' : '';
				}
				if (index == count - 1) {
					imageStr = _treeTableIcons[isFolderNode ? 'minusbottom' : 'joinbottom'];
				} else {
					imageStr = _treeTableIcons[isFolderNode ? (treeNode == rootNode ? 'nolines_minus' : 'minus') : 'join'];
				}
				tdText = indent + '<img src="' + imageStr + '" style="vertical-align: middle" alt="" ' + eventStr + ' />' + iconElement + tdText;
			} else {
				tdText = iconElement + tdText;
			}
			htmlStr += '  <td class="treeTableCell' + (className ? ' ' + className : '') + '" ' + (style ? 'style="' + style + '" ' : '') + '>' + tdText + '</td>\n';
		}
		htmlStr += '</tr>\n';
		for (var i = 0; i < treeNode.nodes.length; i++) {
			var nextIndent = indent + ((index != -1 && index != count - 1) ? '<img src="' + _treeTableIcons['line'] + '" style="vertical-align: middle" alt="" />' : '<img src="' + _treeTableIcons['empty'] + '" style="vertical-align: middle" alt="" />');
			htmlStr += _makeupHTML(treeTable, layout, rootNode, treeNode.nodes[i], i, treeNode.nodes.length, nextIndent);
		}
	}
	return htmlStr;
}

function _get(item, column, treeNode, treeTable) {
	var layout = treeTable.layout;
	return treeNode.item[layout[column].field];
}

function _getIcon(item, column, treeNode, isOpened, tableTree) {
	if (column == 0) {
		if (treeNode.nodes.length > 0) {
			return _treeTableIcons[isOpened ? 'folderopen' : 'folder'];
		} else {
			return _treeTableIcons['page'];
		}
	}
	return '';
}

function _expandNode(treeNode, isOpened) {
	_expand(this, treeNode, isOpened, false);
}

function _expandAll(isOpened) {
	var rootNode = this.getRoot();
	if (rootNode) {
		_expand(this, rootNode, isOpened, true);
	}
}

function _expand(treeTable, treeNode, isOpened, isOpenAll) {
	if (!treeNode) {
		return;
	}

	var subTreeNodes = treeNode.nodes;
	if (subTreeNodes && subTreeNodes.length > 0) {
		var source = document.getElementById('folder_' + treeNode.id);
		var trNode = source.parentNode.parentNode;
		var folderNode = source.nextSibling;
		var itemId = trNode.id;
		var parentNode = source.parentNode;
		while (parentNode.tagName.toLowerCase() != 'table') {
			parentNode = parentNode.parentNode;
		}
		
		folderNode.setAttribute('src', _treeTableIcons[isOpened ? 'folderopen' : 'folder']);
		var isRootNode = treeNode == treeTable.getRoot();
		if (isRootNode) {
			source.setAttribute('src', _treeTableIcons[isOpened ? 'nolines_minus' : 'nolines_plus']);
		} else {
			var isLastTreeNode = treeNode.parent.nodes[treeNode.parent.nodes.length - 1] == treeNode ? true : false;
			if (isLastTreeNode) {
				source.setAttribute('src', _treeTableIcons[isOpened ? 'minusbottom' : 'plusbottom']);
			} else {
				source.setAttribute('src', _treeTableIcons[isOpened ? 'minus' : 'plus']);
			}
		}

		for (var i = 0; i < subTreeNodes.length; i++) {
			var subTreeNode = subTreeNodes[i];
			var subTrNode = document.getElementById(subTreeNode.id);
			if (subTrNode) {
				subTrNode.style.display = isOpened ? 'table-row' : 'none';
			}
			if (!isOpenAll && isOpened && !subTreeNode.isOpened) {
				continue;
			}
			if (isOpenAll) {
				treeNode.isOpened = isOpened;
			}
			_expand(treeTable, subTreeNode, isOpened, isOpenAll);
		}
	}
}

function handleNodeClick(event) {
	var source = event.currentTarget || event.srcElement;
	var trNode = source.parentNode.parentNode;
	var itemId = trNode.id;
	var parentNode = source.parentNode;
	while (parentNode.tagName.toLowerCase() != 'table') {
		parentNode = parentNode.parentNode;
	}
	var treeTable = TreeTable.prototype.instants[parentNode.id];
	var treeNode = treeTable.mapping[itemId];
	var isOpened = treeNode.isOpened;
	treeTable.expandNode(treeNode, !isOpened);
	treeNode.isOpened = !isOpened;
}


默认TableTree.css文件
.treeTable {
	width: 100%;
	border-collapse: collapse;
	border: solid 1px #e8e8e8;
}

.treeTableHeader {
}

.treeTableHeader td {
	height: 20px;
	line-height: 20px;
	font-size: 12px;
	font-weight: bold;
	text-align: center;
}

.treeTableRow {
	margin: 0;
	padding: 0;
}

.treeTableCell {
	height: 25px;
	line-height: 25px;
	font-size: 11px;
	font-weight: bold;
	margin: 0;
	padding: 0;
	border: solid 1px #e8e8e8;
}


------------------------------------------------------
以下是此TreeTable的应用实例:
首先,我们需要一个JSON文件来做模型,这个JSON文件需要是很规范的,而且有层级关系
JSON文件(TreeTableTest.json)的内容如下:
{
	id: 'root',
	name: 'root_node',
	value: 'root_value',
	children: [
		{
			id: 'node_0',
			name: 'node_0_name',
			value: 'node_0_value',
			children: [
				{
					id: 'node_0_0',
					name: 'node_0_0_name',
					value: 'node_0_0_value',
					children: [
						{
							id: 'node_0_0',
							name: 'node_0_0_name',
							value: 'node_0_0_value',
							children: [
								{
									id: 'node_0_0_0',
									name: 'node_0_0_0_name',
									value: 'node_0_0_0_value',
								},
								{
									id: 'node_0_0_1',
									name: 'node_0_0_1_name',
									value: 'node_0_0_1_value',
								}
							]
						},
						{
							id: 'node_0_1',
							name: 'node_0_1_name',
							value: 'node_0_1_value',
							children: [
								{
									id: 'node_0_1_0',
									name: 'node_0_1_0_name',
									value: 'node_0_1_0_value',
								},
								{
									id: 'node_0_1_1',
									name: 'node_0_1_1_name',
									value: 'node_0_1_1_value',
								}
							]
						}
					]
				}
			]
		},
		{
			id: 'node_1',
			name: 'node_1_name',
			value: 'node_1_value',
			children: [
				{
					id: 'node_1_0',
					name: 'node_1_0_name',
					value: 'node_1_0_value',
					children: [
						{
							id: 'node_1_0',
							name: 'node_1_0_name',
							value: 'node_1_0_value',
							children: [
								{
									id: 'node_1_0_0',
									name: 'node_1_0_0_name',
									value: 'node_1_0_0_value',
								},
								{
									id: 'node_1_0_1',
									name: 'node_1_0_1_name',
									value: 'node_1_0_1_value',
								}
							]
						},
						{
							id: 'node_1_1',
							name: 'node_1_1_name',
							value: 'node_1_1_value',
							children: [
								{
									id: 'node_1_1_0',
									name: 'node_1_1_0_name',
									value: 'node_1_1_0_value',
								},
								{
									id: 'node_1_1_1',
									name: 'node_1_1_1_name',
									value: 'node_1_1_1_value',
								}
							]
						}
					]
				}
			]
		}
	]
}


测试用的HTML文件(TreeTableTest.html)的代码如下:
<html>
<head>
	<title>Tree Table Test</title>
	<link rel="stylesheet" type="text/css" href="styles/TreeTable.css" />
	<link rel="stylesheet" type="text/css" href="styles/TreeTableTest.css" />
	<script type="text/javascript" src="js/TreeTable.js"></script>
	<script type="text/javascript" src="js/jquery.min.js"></script>
	<script type="text/javascript" src="js/TreeTableTest.js"></script>
</head>
<body>
	<div id='test_table'></div>
</body>
</html>


因为测试用的代码不想把json对象hardcode到js文件中,所以使用了ajax去读取json对象,引入了jquery的代码,也可以用其它的ajax框架,或直接用xmlRequest对象。

测试用的JS文件(TreeTableTest.js)代码:
$(document).ready(function () {
	$.post('json/TreeTableTest.json?date=' + new Date().valueOf(), {type:"slides"}, function (data) {
		initTreeTable(data);
	});
})

function initTreeTable(data) {
	json = eval('(' + data + ')');
	model = {
		store: json,
		childrenAttrs: ['children']
	};
	layout = [
		{name: 'Id', field: 'id', headerClass: 'id_col', className: 'id_col', style: 'width: 20%'},
		{name: 'Name', field: 'name', headerClass: 'name_col', className: 'name_col', style: 'width: 60%', get: testGetName, getIcon: testGetIcon},
		{name: 'Value', field: 'value', headerClass: 'value_col', className: 'value_col', style: 'width: 20%', get: testGetValue}
	];
	var treeTable = new TreeTable(layout, model, 'test_table');
	treeTable.startup();
//	treeTable.expandAll(false);
}

function testGetName(item) {
	return '<a href="javascript:;">' + item.id + '</a>';
}

function testGetValue(item, column, treeNode) {
	if (treeNode.nodes.length == 0) {
		return '<input type="text" value="' + item.value + '"/>';
	}
	return '';
}

function testGetIcon(item) {
	return 'images/page.gif';
}


目前TreeTable支持每个单元格的css, style和icon的定制,且方法极其简单。对于列和单元格中的数据展示都可以定制,很灵活。

需要的css文件(TestTreeTable.css)代码如下:
.id_col {
	background: yellow;
}

.name_col {
	background: gray;
}

.value_col {
	border: green;
}

.value_col input {
	margin: 0;
	padding: 0;
	height: 16px;
	width: 100%;
}


以后装要完成的需求:
1.基于Javascript实现
2.支持通过程序控制的方式来实现动态的修改节点
3.支持展开,收缩等等标准操作
4.支持异步加载数据的方式
5.在编程控制方面,完成基本的设置(Javascript文件的引用或者css中behavior的声明)之后就可以基于对象的控制

扩展性
6.支持拖动
7.支持自定义右键菜单
7.在frame布局中支持target方式的自动链接
8.支持tooltip
1 楼 tianlihu 2010-06-17  
fancool 2010-06-12

你好 关于你的treetable文章 看了下 不知道你有没有提供getNode的方法 比如我选中一个节点 然后可以getNode来获取该节点的json格式数据 谢谢

回答

function getNode(trId) {
	var trNode = document.getElementById(trId);
	if (trNode) {
		var parentNode = trNode.parentNode;
		while (parentNode.tagName.toLowerCase() != 'table') {
			parentNode = parentNode.parentNode;
		}
		var treeTable = TreeTable.prototype.instants[parentNode.id];
		return treeTable.mapping[trId];
	}
	return null;
}
2 楼 fancool 2010-06-17  
tianlihu 写道
fancool 2010-06-12

你好 关于你的treetable文章 看了下 不知道你有没有提供getNode的方法 比如我选中一个节点 然后可以getNode来获取该节点的json格式数据 谢谢

回答

function getNode(trId) {
	var trNode = document.getElementById(trId);
	if (trNode) {
		var parentNode = trNode.parentNode;
		while (parentNode.tagName.toLowerCase() != 'table') {
			parentNode = parentNode.parentNode;
		}
		var treeTable = TreeTable.prototype.instants[parentNode.id];
		return treeTable.mapping[trId];
	}
	return null;
}


非常感谢!
3 楼 tianlihu 2010-06-29  
目前些TreeTable没有实现编辑功能,还有就是模型的事件通知功能,可以采用MVC做,利用模型驱动
  相关解决方案