最终效果图:
UI说明:针对table本身进行增强的tree table组件。
tree的数据来源是单元格内a元素的自定义属性:level和type。具体代码如下:
Department EmployeeID position
Dept4 - -
fanggw c3025 MASTER
team1 - -
zhanghy c3268 SE
chenf c3401 SE
根据上述数据源结构,先遍历该table,读取数据并建立整课树的数据模型,然后初始化整棵树的视图(node和leaf的显示由css样式定义,方便修改,如果需要可以进一步在初始化的时候由外部代码指定),并关联节点的click处理程序。
下面是主要的实现代码:
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
var Node = Class.create();
Node.prototype = {
initialize: function(link, level, type) {
this.name = link.innerText;
this.id;
this.link = link;
this.type = type;
this.level = level;
this.isOpen = true;
this.isClicked = false;
this.root;
this.img; //clicked img's path
this.parent;
this.children = new Array();
this.getChildren();
},
getChildren: function() {
if (this.type == "node") {
//alert(this.link.innerText);
var dataRows = document.getElementById("treeGrid").getElementsByTagName("TBODY")[0].getElementsByTagName("TR");
var pushFlag = false;
for(var j=0; j0; lvl--) {
var indentImg = document.createElement("img");
//get parent node by level
var parentNode = this.parent;
for (var i=1; i 0) {
if (this.getNext()) {
path = "./images/Tminus.gif";
} else {
path = "./images/Lminus.gif";
}
}
else {
if (this.getNext()) {
path = "./images/T.gif";
} else {
path = "./images/L.gif";
}
}
}
} else {
if (this.getNext()) {
path = "./images/T.gif";
}
else {
path = "./images/L.gif";
}
}
img.src = path;
img.align = "absbottom";
//set cursor pointer style to the minus/plus img
img.style.cursor = "pointer"
this.img = img;
img.onclick = expand;
oFragment.appendChild(img);
oFragment.appendChild(this.link);
var div = document.createElement("div");
div.setAttribute("id", this.id);
/* div css class set by type */
div.className = (this.type=="node")?"node":"leaf";
/* all node is margin to left by 10 pixel except root */
if (this.level > 0) {
div.style.marginLeft = "10px";
}
div.appendChild(oFragment);
return div;
}
}
/* global variable */
//tree root
var root;
//all nodes of the tree
var nodes = new Array();
/* initialize the whole tree grid */
function initTreeGrid() {
//dataRows is the datasource of the tree
var dataRows = document.getElementById("treeGrid").getElementsByTagName("TBODY")[0].getElementsByTagName("TR");
//find the root of the tree
for (var i=0; i 0) {
initNodes(node.children[j]);
}
}
}
/* expand row elements by isOpen flag */
function expand() {
var currentDivId = event.srcElement.parentNode.id;
var currentNode;
//get the clicked node
for(var i=0; i
该组件已在IE6+,Firefox上测试通过。
有兴趣的朋友可以联系我,进行进一步的改进和扩展。