先看看效果吧:
為DTree添加上複選框可以讓樹的功能更加豐富,比如在做樹形結構的時候可以點擊選擇多個樹節點進行操作等等....
添加複選框的步驟:
1)dtree.js
在function dTree
(objName) {
this.config = {
target : null,
folderLinks : true,
useSelection : true,
useCookies : true,
useLines : true,
useIcons : true,
useStatusText : false,
closeSameLevel : false,
inOrder : false,
check : true
// 檢查是否有複選框
}
添加上check屬性.
2)dtree.js
添加代碼:
dTree.prototype.node = function(node, nodeId) {
var str = '<div class="dTreeNode">' + this.indent(node, nodeId);
if (this.config.useIcons) {
if (!node.icon)
node.icon = (this.root.id == node.pid)
? this.icon.root
: ((node._hc) ? this.icon.folder : this.icon.node);
if (!node.iconOpen)
node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node;
if (this.root.id == node.pid) {
node.icon = this.icon.root;
node.iconOpen = this.icon.root;
}
str += '<img id="i' + this.obj + nodeId + '" src="'
+ ((node._io) ? node.iconOpen : node.icon) + '" alt="" />';
//添加上複選框
if (this.config.check == true) {
str += '<input type="checkbox" id="c' + this.obj + node.id
+ '" onclick="javascript:' + this.obj + '.cc(' + node.id
+ ',' + node.pid + ')"/>';
}
}
3)dtree.js
最後要為點中複選框的事件添加cc方法
//點擊複選框onclick事件
dTree.prototype.cc=function(nodeId, nodePid){
//首先擷取這個多選框的id
var cs = document.getElementById("c" + this.obj + nodeId).checked;
var n,node = this.aNodes[nodeId];
var len = this.aNodes.length;
for (n=0; n<len; n++) { //如果迴圈每一個節點
if (this.aNodes[n].pid == nodeId) { //如果選中的是非葉子節點,則要將所有的子節點選擇和父節點一樣
document.getElementById("c" + this.obj + this.aNodes[n].id).checked = cs;
this.cc(this.aNodes[n].id, nodeId);
}
}
if(cs==true){ //當前是選中狀態
var pid=nodePid;
var bSearch;
do{
bSearch=false;
for(n=0;n<len;n++){ //迴圈每一個節點
if(this.aNodes[n].id==pid){ //如果迴圈的節點的id等於PID
document.getElementById("c"+this.obj+pid).checked=true; //那麼這個迴圈的節點應該被選中
pid=this.aNodes[n].pid;
bSearch= true;
break;
}
}
}while(bSearch==true);
}
if(cs==false){ //如果被取消選擇
var pid = nodePid;
do{
for(j=0;j<len;j++){ //迴圈每一個多選框 如果這個節點的子節點有其他是選中的,則不取消
if(this.aNodes[j].pid==pid && document.getElementById("c" + this.obj + this.aNodes[j].id).checked==true){
return;
}
}
if(j==len){ //迴圈結束
for(k=0;k<len;k++){
if(this.aNodes[k].id==pid){ //如果找到父節點
document.getElementById("c"+this.obj+this.aNodes[k].id).checked=false;
pid=this.aNodes[k].pid;
break;
}
}
}
}while(pid!=-1);
}
}
//複選框onclick事件
恭喜!完成以上三步後,dtree的複選框就打造完成了
建立一顆樹:
d = new dtree('d');
d.check = true; //
只添加了這一段代碼
d.add.......
................