2012年6月19日 星期二

以JS code 的OO方法實現樹狀結構

出處:hkepc 討論區原貼

效果


 food
       fruit
          Red
             Cherry
          Yellow
             Banana
       Meat
          Beef
          Pork
 

Tree hierarchy: (在 IE 下不能正常運行)



JS code
<script language="javascript">
<!--

var $ = function(_id) {return document.getElementById(_id);};

function Node(nodeName,nodeParentID, indentNum){
        this.nodeName = nodeName;
        this.nodeParentID = nodeParentID;
        this.childNodes = [];
        this.add=function(node){
                        this.childNodes[this.childNodes.length] = node;
                };
}

function createTree(){
        var dataAry = [
/*0*/                ["root"-1],
/*1*/                ["food",0],
/*2*/                ["fruit",1],
/*3*/                ["Meat",1],
/*4*/                ["Red",2],
/*5*/                ["Yellow",2],
/*6*/                ["Cherry",4],
/*7*/                ["Banana",5],
/*8*/                ["Beef",3],
/*9*/                ["Pork",3]
        ];
        
        var tmpAry=[]; 
        for(var i=0;i<dataAry.length;i++){
                tmpAry[tmpAry.length]= new Node(dataAry[i][0], dataAry[i][1]);
        }

        for(var i=1;i<tmpAry.length;i++){
                var parentIdx = dataAry[i][1];
                tmpAry[parentIdx].add(tmpAry[i]);
        }

        return tmpAry[0];
}

var debugtxt = [];

function debug(msg){
        debugtxt[debugtxt.length] = msg;
}


function walkTree(aTreeNode, indent){
        for(var i=0;i<aTreeNode.childNodes.length;i++){
                debug(indent + aTreeNode.childNodes[i].nodeName + "<br/>");
                
                var subNodes = aTreeNode.childNodes[i].childNodes;                                                                
                if (subNodes.length>0) {
                        walkTree(aTreeNode.childNodes[i], "   " + indent);
                }
        }
}

var treeRoot=null;
function printHierarchy(){
        debugtxt = [];        
        treeRoot = createTree();        
        walkTree(treeRoot, "");

        $("tree1").innerHTML = debugtxt.join("");
}

function clearHierarchy(){
        $("tree1").innerHTML = "";
}
//-->
</script>

html code
Tree hierarchy: <br>
<input type="button" onClick="printHierarchy();" value="Print hierarchy">
<input type="button" onClick="clearHierarchy();" value="Clear data">
<div id="tree1"></div>
延伸閱讀:

google 搜索 樹狀結構
php實現樹狀結構無級分類

沒有留言: