一、为什么需要动态显示的目录树
       由于用目录树显示数据层次性强,在web页面中目录树的使用可以说是随处可见.其实现方法也有好几种.
       方案一.  我们可以直接去msdn去下载webcontrol包,里面包含了一个TreeView控件,它是一个web的服务器端控件,添加引用之后,就可以直接添加到页面中了,开发起来也很简单,数据既可以直接添加,也可以通过数据绑定动态添加,但是它的缺点也很明显:由于每次显示时,它把需要显示的数据全部都加载,如果数据量很大的话,效率可想而知.
     方案二.  我们也可以用javascript编写,然后用css控制它的样式,由于javascript是在客户端运行的,这种方案实现的目录树减轻了服务器的负担,但是显示的数据不能动态绑定.
     试想一个这样的应用环境:我们需要把上万个文件夹和文件用一个目录树加载,文件夹中可以包含多个目录和文件,而这些文件夹和文件的信息都保存在数据库中,我们该怎么做?方案一和方案二显然都行不通,这时我们可以先把第一层目录加载在页面中显示出来(不是全部加载),其它的目录和文件就按需显示,即什么时候用户请求显示,内容什么时候加载.

二、如何实现
 在客户端
JavaScript代码:
function InsertChildTree1(str,o)
{
if(o==null || o.parentNode==null || str==null)
            
{
alert(
"Error.  [3000] object expected!");
return;
}


if(o.parentNode.className=="Closed")return;
if(o.IsLoad)
{
   
if(o.IsLoad=="1")return;
}


var response=TreeData.InsertTreeData(str);
var ds=response.value;
if(ds != null && typeof(ds) == "object" && ds.Tables != null)
{

  
for(var i=0;i<ds.Tables[0].Rows.length;i++)
   
{  
    
var oNewList=document.createElement("ul");
      o.parentNode.appendChild(oNewList); 
      
var oNewNode = document.createElement("li");
      oNewList.appendChild(oNewNode);
      oNewNode.className
="Closed";
       
var oNodeImg=document.createElement("img");
      
      oNodeImg.setAttribute(
"IsLoad","0");
      
      
var strPath;
      
var subCount=ds.Tables[0].Rows[i].NodeCount;
      
     strPath
=ds.Tables[0].Rows[i].NodePath;
      oNodeImg.setAttribute(
"strPath",strPath);
      oNodeImg.className
="s";
     oNewNode.appendChild(oNodeImg);
     
    
if(subCount>0)
     
{
      oNodeImg.onclick
=function(){ChangeStatus(this);InsertChildTree1(this.strPath,this);this.IsLoad="1";};
      oNodeImg.src
="css/s.gif";
     }

     
else
     
{
     oNodeImg.src
="css/s.gif";
     oNodeImg.parentNode.className
="Child";
     }

      
      
     
var oNodeHref=document.createElement("a");
      oNodeHref.setAttribute(
"strPath",strPath);
      
        oNodeHref.setAttribute(
"href","#");
      oNodeHref.onclick
=function(){ViewFolder(this.strPath);};
      
      oNodeHref.innerText
=ds.Tables[0].Rows[i].NodeText;
       
if(subCount<0)subCount=0;
         oNodeHref.setAttribute(
"title","此目录下共有"+subCount+"个子文件夹");
    
      oNewNode.appendChild(oNodeHref);
      
    }
 
      
}

else
{
alert(
"Error. [3001] " + response.request.responseText); 
}


}

 

function write(o)
{
if(typeof(o.request)!="object")return;

 
if(o.request.readyState==1   && o.request!=null)
 
{
 alert(
"ffff");

 }

 
else
 
{
  
return;
 }

}


//添加子树
function InsertChildTree(o)
{

if(o.className=="Closed"  )

if(o.IsLoad)
{
 
if(o.IsLoad=="1")return;
}



var response=TreeData.InitTreeData1();

  write(response);
 
var ds = response.value;
if(ds != null<%2
posted on 2006-12-27 16:51  FlyBird  阅读(3074)  评论(0)    收藏  举报