關於合成模式的javascript的一個treeview例子

來源:互聯網
上載者:User

合成模式的意思是說用一個對象載入另外一個對象進來而形成的,非常適合樹型結構,也很類似鏈表結構

下面舉一個我寫的javascript的treeview做例子

   var treebase = {
 rootnum        : 0 
};

   function treeview(nodetxt,nodehref,nodetag){
     this.childNodes=[];
  this.txt=nodetxt;
  if(nodehref==null)
   this.href="";
  else
  this.href=nodehref;
  this.target=nodetag;
  if(this.parentNode==null)
  {
    this.id="root_"+treebase.rootnum;
    treebase.rootnum=treebase.rootnum+1;
  }
 }

   treeview.prototype.toString=function(){
      var str="<div>";
   var c_node=this;
   while(c_node.parentNode)
   {
      str=str+"1";
   c_node=c_node.parentNode;
   }
   if (this.childNodes.length!=0)
   {
    if(this.href.length>0)
   str=str+"<a href='"+this.href+"' target='"+this.target+"' onclick=/"javascript:showdiv('"+this.id+"_child')/">"+this.txt+"</a>";
    else     
   str=str+"<a href=/"javascript:showdiv('"+this.id+"_child')/">"+this.txt+"</a>";
    }
    else
    {
        if(this.href.length>0)
   str=str+"<a href='"+this.href+"' target='"+this.target+"'>"+this.txt+"</a>";
    else     
   str=str+this.txt;
  }  
  
    
   if (this.childNodes.length!=0)
   {
     str=str+"<div style=/"display:none;/" id=/""+this.id+"_child/">";
  
   //var save_pos=new Array();
  // save_pos.add(this.id);
    for(var int_len=0;int_len<this.childNodes.length;int_len++)
   { 
   //save_pos.push(this.id,int_len);
   str=str+this.childNodes[int_len];
   //int_len=save_pos.find(this.id);
    }  
  str=str+"</div>";
   }
  
   str=str+"</div>";
   return str;
   }

   function showdiv(div_id){
    var obj_id=document.getElementById(div_id);
 obj_id.style.display=(obj_id.style.display=='none'?'block':'none');
   }

   treeview.prototype.add=function(node){
     node.parentNode=this;
     this.childNodes[this.childNodes.length]=node;
  if (node.childNodes.length==0)
  {
    node.id=this.id+"_child"+this.childNodes.length;    
   }
  if(node.target==null){
   node.target=this.target;
  }
   } 

 

這裡就是用parentNode記錄當前對象而形成了一個雙鏈結構

用的時候

var node1=new treeview("node1");
var node2=new treeview("node2");
node1.add(node2);
document.write(node1);
這樣就可以了

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.