日期:2012-11-28  浏览次数:20834 次

三、客户端代码

   下面是程序的启动页面Tree.htm:

 < HTML >
   < SCRIPT SRC="Renderer.js" LANGUAGE="JavaScript" >< /SCRIPT >
   < HEAD >< /HEAD >
   < BODY ID=bodyTree NAME="bodyTree" OnLoad="GetTree();" >
     < IFRAME ID=GetData STYLE="display:none"  >< /IFRAME >
   < /BODY >
 < /HTML >
   该页面装载时将执行Renderer.js中的GetTree函数。HTML代码中的IFRAME部分实现了客户端和服务器端的通讯机制。JavaScript函数GetTree的代码如下:

 function GetTree() {
    if (event.type == 'load') {
       if (typeof(divTree0)!='object')
          GetData.window.location.href = 'GetTreeData.asp?Level=0';
    } else {
       try {
          objManip = eval('divTree' + event.srcElement.getAttribute('ElementId'));
          if (objManip.style.display == 'none') {
             objManip.style.display = '';
          } else {
             objManip.style.display = 'none';
          }
       } catch (e) {
          GetData.window.location.href = 'GetTreeData.asp?Level=' + event.srcElement.getAttribute('ElementId');
       }
       event.cancelBubble = true;
    }
 }
   当文档装载时,onload事件被触发,GetTree函数得以执行。函数检查容器divTree0是否存在,并为IFRAME(ID为GetData)读取第一层节点(这些节点的父节点ID为0)。如前所述,所有的节点都必须处理鼠标单击事件,而且事件句柄都是GetTree函数。当某个节点(如div1)接收到一个鼠标事件时,程序将执行GetTree函数中的else部分。如果发送该事件的节点已经读取了子节点,则程序检查这些子节点是否已经显示,然后切换子节点的显示状态,从而实现了该层节点的扩展或折叠效果。检查子节点是否显示的if语句封装在一个try块内,因此当子节点不存在时,程序将执行catch部分,调用服务器脚本GetTreeData.asp读取子节点内容。最后,程序设置event.cancelBubble = true,目的是禁止上一层容器处理该事件。

   服务器脚本GetTreeData.asp返回的HTML代码类如:

 < HTML >
    < BODY OnLoad="parent.PopulateTree('1|0|节点1|2|0|节点2|3|0|节点3|4|0|节点4|');" >
    < /BODY >
 < /HTML >
   可以看到,这里的Onload事件又调用了另外一个JavaScript函数PopulateTree。PopulateTree函数代码如下:

 function PopulateTree(strData) {
    var arrSplitData;
    var iCnt;
    var objTempDiv;
    var objMainDiv;
 
    if (strData=='') return;
    arrSplitData = strData.split("|");
 
    objMainDiv = document.createElement('DIV');
    objMainDiv.id = 'divTree' + arrSplitData[1];
    objMainDiv.style.cssText = 'position:relative;left:10px;cursor:hand;';
    for (iCnt=0;iCnt< arrSplitData.length-1;iCnt+=3) {
       objTempDiv = document.createElement('< DIV OnClick='GetTree()' OnSelectStart='return false;' >');
       objTempDiv.id = 'div' + arrSplitData[iCnt];
       objTempDiv.innerHTML = arrSplitData[iCnt+2];
       objTempDiv.setAttribute('ElementId',arrSplitData[iCnt]);
       objTempDiv.setAttribute('ParentElementId',arrSplitData[iCnt+1]);
       objTempDiv.style.cssText = 'position:relative;cursor:hand;color:red;width:100px;font-size:x-small;';
       objMainDiv.appendChild(objTempDiv);
    }