利用Ajax实现树的动态加载

来源:互联网 发布:迅捷流程图制作软件 编辑:程序博客网 时间:2024/04/28 00:19

      在很多项目中我们都会用到树,或者用类似的TreeView控件,或者直接用JavaScript和HTML来直接实现。一般情况下,我们都是一次性将所有的节点都加载到树上,当树的节点不是很多的情况下倒没什么问题,但是如果树的节点数很多的时候就影响显示效率了。

       去年曾经在一个项目里用树结构来显示一个单位的岗位,在实际环境中岗位数多达两三千个,利用传统的方法一次性将所有岗位都加载到树上时,用户打开这个页面到显示完这个树控件需要等待很长时间(长达几分钟),严重影响了UT体验。于是我就开始查找在哪里出了问题,为什么这么个树需要等待这么久时间才能显示出来呢?

        首先我怀疑是从数据库里一次性取出所有树节点数据消耗了很多时间,但经过仔细分析和测试,从数据库取几千条数据是很正常的事情,所用的时间非常少,这不是影响树显示的主要原因。而且将这些数据组织成一个有序数组也是很快就完成了。然后猜想是不是这些节点生成的HTML代码太多,所以网络传输耗了太多时间? 但经过测试后这个原因也被排除了。最后才确定了主要原因在于在客户端将所有这些节点组织成一棵完整的树显示出来消耗了大部分时间。(在数据量特别大的情况下,前两种分析是会影响树的效率的)

        为了解决这个问题,我就尝试动态加载树节点,即在初始化时只加载少数节点(如只加载根节点或加载第一级节点),然后当用户点击展开某个节点时再动态加载该节点的子节点,如图(下载完整示例代码):

   

       实际原理非常简单,树的组织利用JavaScript(Tigra Tree)来实现,动态加载节点利用了Ajax技术。在此将大致思路记录一下,但没有对整个Tree做进一步的封装。

  

(一) 负责组织树的JavaScript代码( NodeDyn.js )

  1. onefolder    = false
  2. norootclose  = true
  3. norootselect = true
  4. closesubs    = false
  5. function tree (a_items, a_template, f_getchild,treeContainerId ) 
  6. {
  7.     this.a_tpl      = a_template;
  8.     this.a_config   = a_items;
  9.     this.o_root     = this;
  10.     this.a_index    = [];
  11.     this.o_selected = null;
  12.     this.n_depth    = -1;
  13.     this.f_getchild = f_getchild;       //取下级结点的函数 
  14.     
  15.     var o_icone = new Image(),
  16.         o_iconl = new Image();
  17.     o_icone.src = a_template['icon_e'];
  18.     o_iconl.src = a_template['icon_l'];
  19.     a_template['im_e'] = o_icone;
  20.     a_template['im_l'] = o_iconl;
  21.     for (var i = 0; i < 64; i++)
  22.         if (a_template['icon_' + i]) {
  23.             var o_icon = new Image();
  24.             a_template['im_' + i] = o_icon;
  25.             o_icon.src = a_template['icon_' + i];
  26.         }
  27.     
  28.     //add by ghqian 2007-10-12 
  29.     this.toggleByItem = tree_toggleByItem;
  30.     this.toggleByData = tree_toggleByData;          //只能展开已经生成的节点,不处理待动态生成的节点 
  31.     this.selectByData = tree_selectByData;          //展开到指定节点(不处理待动态生成的节点),选择该节点 
  32.         
  33.     this.toggle = function (n_id) 
  34.     {       
  35.         var o_item = this.a_index[n_id]; 
  36.         this.toggleByItem( o_item , false )     
  37.     };
  38.         
  39.     this.select = function (n_id) 
  40.     { 
  41.         return this.a_index[n_id].select(); 
  42.     };
  43.         
  44.     this.mout   = function (n_id) 
  45.     { 
  46.         this.a_index[n_id].upstatus(true
  47.     };
  48.     
  49.     this.mover  = function (n_id) 
  50.     { 
  51.         this.a_index[n_id].upstatus() 
  52.     };
  53.     this.a_children = [];
  54.     for (var i = 0; i < a_items.length; i++)
  55.         new tree_item(this, i);
  56.     this.n_id = trees.length;
  57.     trees[this.n_id] = this;
  58.     
  59.     //HTML Container add by ghqian 2007-10-24 
  60.     var container = null;
  61.     if( treeContainerId )
  62.         container = document.getElementById(treeContainerId);
  63.     
  64.     if( container)
  65.         container.innerHTML = "";
  66.     
  67.     for (var i = 0; i < this.a_children.length; i++) 
  68.     {   
  69.         var mHtml = this.a_children[i].init();
  70.         if( container )
  71.             container.innerHTML += mHtml;
  72.          else
  73.             document.write( mHtml );
  74.         this.a_children[i].open();
  75.     }
  76. }
  77. ////////////// toggle & select by data Add by ghqian 2007-10-12/////////////////// 
  78. //展开到指定节点(不处理待动态生成的节点),选择该节点 
  79. //如果runEvent为true,同时出发对应事件 
  80. function tree_selectByData( m_data, runEvent )
  81. {
  82.     forvar i=0;i<this.a_index.length;i++)
  83.     {
  84.         var o_item = this.a_index[i];
  85.         if( o_item.m_data==m_data )
  86.         {
  87.             var parentItem = o_item.o_parent;
  88.             if( parentItem != null )
  89.                 this.toggleByItem(parentItem ,true);                    
  90.             //this.toggleByItem(o_item,true); 
  91.             
  92.             o_item.select();
  93.             if( runEvent )
  94.                 eval( o_item.a_config[1] );
  95.             return;             
  96.         }
  97.     }   
  98. }
  99. function tree_toggleByItem( o_item, toggleParent )
  100. {
  101.     if( o_item && o_item.n_depth>-1)        
  102.     {    
  103.         if( toggleParent )
  104.         {
  105.             var parentItem = o_item.o_parent;
  106.             if( parentItem && parentItem.n_depth>-1 && !parentItem.b_opened )
  107.                 this.toggleByItem( parentItem, toggleParent );
  108.         }
  109.         
  110.         if( o_item && !o_item.b_opened) 
  111.         {
  112.             if (onefolder) 
  113.                 expand_or_collapse_level(this,o_item.n_depth)
  114.         };
  115.         o_item.open(o_item.b_opened) 
  116.      }
  117. }
  118.     
  119. //根据m_data 展开  Add by ghqian 2007-10-11 
  120. function tree_toggleByData( m_data )
  121. {
  122.     forvar i=0;i<this.a_index.length;i++)
  123.     {
  124.         var o_item = this.a_index[i];
  125.         if( o_item.m_data==m_data )
  126.         {
  127.             this.toggleByItem(o_item,true);
  128.             return;             
  129.         }
  130.     }
  131. }
  132. ///////////////////////////////////////// 
  133. function tree_item (o_parent, n_order) {
  134.     this.n_depth  = o_parent.n_depth + 1;
  135.     this.a_config = o_parent.a_config[n_order + (this.n_depth ? 4 : 0)];
  136.     if (!this.a_config) return;
  137.     this.o_root    = o_parent.o_root;
  138.     this.o_parent  = o_parent;
  139.     this.n_order   = n_order;
  140.     this.b_opened  = !this.n_depth;
  141.     this.b_havechild = this.a_config[2];    //add by ghqian 
  142.     this.m_data      = this.a_config[3];    //add by ghqian  
  143.     this.n_id = this.o_root.a_index.length;
  144.     this.o_root.a_index[this.n_id] = this;
  145.     o_parent.a_children[n_order] = this;
  146.     this.a_children = [];
  147.     for (var i = 0; i < this.a_config.length - 4; i++)
  148.         new tree_item(this, i);
  149.     this.get_icon = item_get_icon;
  150.     this.open     = item_open;
  151.     this.select   = item_select;
  152.     this.init     = item_init;
  153.     this.upstatus = item_upstatus;
  154.     
  155.     this.is_last  = function () 
  156.     { 
  157.         return this.n_order == this.o_parent.a_children.length - 1 
  158.     };
  159. }
  160. //将item的子结点生成HTML联合起来放到o_idiv里  add by ghqian 2007-10-11 
  161. function item_open_joinChildHtml(o_idiv,item)
  162. {
  163.     var a_children = [];        
  164.     for (var i = 0; i < item.a_children.length; i++) 
  165.         a_children[i]= item.a_children[i].init();
  166.     
  167.     o_idiv.innerHTML = a_children.join('');
  168. }
  169. //处理item_open的善后问题 add by ghqian 2007-10-11 
  170. function item_open_tail(o_idiv,item,b_close)
  171. {
  172.     var o_jicon = document.images['j_img' + item.o_root.n_id + '_' + item.n_id],
  173.         o_iicon = document.images['i_img' + item.o_root.n_id + '_' + item.n_id];
  174.     
  175.     //判断是否取到了下级数据,取不到下级数据时做如下处理 
  176.     if( o_idiv.innerHTML=="" )
  177.     {       
  178.        //移除DIV 
  179.        if( o_idiv.parentNode )
  180.          o_idiv.parentNode.removeChild( o_idiv );
  181.        else
  182.          o_idiv.style.display="none";           
  183.     
  184.         //替换加减号等图片 
  185.         item.b_opened = false;          
  186.         item.b_havechild = false;
  187.         if (o_jicon) o_jicon.src = item.get_icon(true); 
  188.         
  189.         //移出<a>元素的事件 
  190.         var po = o_jicon.parentNode;
  191.         if( po )
  192.         {               
  193.             po.outerHTML = po.innerHTML;
  194.         }
  195.     }
  196.     else
  197.     {       
  198.         item.b_opened = !b_close;           
  199.         if (o_jicon) o_jicon.src = item.get_icon(true);
  200.     }       
  201.     
  202.     if (o_iicon) o_iicon.src = item.get_icon();
  203.     item.upstatus();
  204. }
  205. //添加临时节点,提示Loading... add by ghqian 2007-10-11 
  206. function item_open_addTipItem(o_idiv,item)
  207. {
  208.     item.a_config[item.a_config.length] = ["<strong>Loading...</strong>","",false];
  209.     var tipItem = new tree_item(item,0);            
  210.     o_idiv.innerHTML = tipItem.init();       
  211.     item.a_config.splice( item.a_config.length-1,1 );
  212.     item.a_children.splice( 0,item.a_children.length );
  213. }
  214. //动态添加下级节点 add by ghqian 2007-10-11 
  215. function item_open_dynGetChild(o_idiv,item,b_close)
  216. {
  217.     //取下级结点          
  218.     var childItem = item.o_root.f_getchild(item.m_data);
  219.     if( childItem )
  220.     {               
  221.         forvar m=0;m<childItem.length;m++)
  222.             item.a_config[item.a_config.length] = childItem[m];
  223.     }
  224.     for (var i = 0; i < item.a_config.length - 4; i++) 
  225.         new tree_item(item, i); 
  226.         
  227.     item_open_joinChildHtml(o_idiv,item);
  228.     //善后 
  229.     item_open_tail(o_idiv,item,b_close) 
  230. //modify by ghqian 2007-10-11  修正Loading... 
  231. function item_open (b_close) 
  232. {
  233.      if (!(this.n_depth==0 && b_close && norootclose)) 
  234.      {  //**** to avoid collapsing of first voice 
  235.         //**** Added to close subfolders **** 
  236.         if (!manageall && closesubs) 
  237.         {
  238.             for (var i = 0; i < this.a_children.length; i++)
  239.                 this.a_children[i].open(true)
  240.         }
  241.         //*********************************** 
  242.         
  243.         var meItem = this;      //add by ghqian 2007-10-11 
  244.         var o_idiv = get_element('i_div' + this.o_root.n_id + '_' + this.n_id);
  245.         if (!o_idiv) return;
  246.         
  247.         o_idiv.style.display = (b_close ? 'none' : 'block');
  248.         
  249.         if (!o_idiv.innerHTML) 
  250.         {       
  251.             //如果没有下级结点,但属性显示有下级结点,说明需要动态加载下级结点 
  252.             if( !this.a_children.length && this.b_havechild )
  253.             {
  254.                 //将提示信息结点加上去 
  255.                 item_open_addTipItem(o_idiv,meItem);
  256.                 
  257.                 //取下级结点          
  258.                 setTimeout( function(){ item_open_dynGetChild(o_idiv,meItem,b_close) } ,0)
  259.                 return;                 
  260.             }
  261.                 
  262.             item_open_joinChildHtml(o_idiv,meItem);
  263.         }
  264.         
  265.         //善后 
  266.         item_open_tail(o_idiv,meItem,b_close)       
  267.      }  
  268. }
  269. function item_select (b_deselect) 
  270. {
  271. //     if (!(this.n_depth==0 && norootselect)) {  //**** to avoid selection of first voice 
  272.     if (!b_deselect) 
  273.     {
  274.         var o_olditem = this.o_root.o_selected;
  275.         this.o_root.o_selected = this;
  276.         if (o_olditem) o_olditem.select(true);
  277.     }
  278.     
  279.     var o_iicon = document.images['i_img' + this.o_root.n_id + '_' + this.n_id];
  280.     if (o_iicon) 
  281.         o_iicon.src = this.get_icon();
  282.         
  283.     get_element('i_txt' + this.o_root.n_id + '_' + this.n_id).style.fontWeight = b_deselect ? 'normal' : 'bold';
  284. //     } 
  285.      this.upstatus();
  286.      return Boolean(this.a_config[1]);
  287.         
  288. }
  289. function item_upstatus (b_clear) 
  290. {
  291.     //window.setTimeout('window.status="' + (b_clear ? '' : this.a_config[0] + (this.a_config[1] ? ' ('+ this.a_config[1] + ')' : '')) + '"', 10); 
  292. }
  293. function item_init () 
  294. {   
  295.     var a_offset = [],
  296.         o_current_item = this.o_parent;
  297.         
  298.     for (var i = this.n_depth; i > 1; i--)
  299.     {
  300.         a_offset[i] = '<img src="' + this.o_root.a_tpl[o_current_item.is_last() ? 'icon_e' : 'icon_l'] + '" border="0" align="absbottom">';
  301.         o_current_item = o_current_item.o_parent;
  302.     }
  303.     
  304.     return '<table cellpadding="0" cellspacing="0" border="0"><tr><td nowrap>' + 
  305.             (this.n_depth ? 
  306.                            a_offset.join('') + (
  307.                                                  (this.a_children.length>0||this.b_havechild) ?
  308.                                                        '<a onfocus=this.blur() href="" onClick="trees[' + this.o_root.n_id + '].toggle(' + this.n_id + ');trees[' + this.o_root.n_id + '].select(' + this.n_id + ');return false" onmouseover="trees[' + this.o_root.n_id + '].mover(' + this.n_id + ')" onmouseout="trees[' + this.o_root.n_id + '].mout(' + this.n_id + ')"><img src="' + this.get_icon(true) + '" border="0" align="absbottom" name="j_img' + this.o_root.n_id + '_' + this.n_id + '"></a>'
  309.                                                        : '<img src="' + this.get_icon(true) + '" border="0" align="absbottom">')
  310.                             : ''
  311.                      + '<a href="#" onfocus=this.blur();  onclick=trees[' + this.o_root.n_id + '].select(' + this.n_id + ');'+this.a_config[1]+' ondblclick="trees[' + this.o_root.n_id + '].toggle(' + this.n_id + ');return trees[' + this.o_root.n_id + '].select(' + this.n_id + ')" onmouseover="trees[' + this.o_root.n_id + '].mover(' + this.n_id + ')" onmouseout="trees[' + this.o_root.n_id + '].mout(' + this.n_id + ')" class="t' + this.o_root.n_id + 'i" id="i_txt' + this.o_root.n_id + '_' + this.n_id + '"><img src="' + this.get_icon() + '" border="0" align="absbottom" name="i_img' + this.o_root.n_id + '_' + this.n_id + '" class="t' + this.o_root.n_id + 'im">' + this.a_config[0] + '</a></td></tr></table>' + ((this.a_children.length>0||this.b_havechild) ? '<div id="i_div' + this.o_root.n_id + '_' + this.n_id + '" style="display:none"></div>' : '');
  312. }
  313. function item_get_icon (b_junction) 
  314. {   
  315.     return this.o_root.a_tpl['icon_' + ((this.n_depth ? 0 : 32) + ((this.a_children.length>0||this.b_havechild) ? 16 : 0) + ((this.a_children.length>0||this.b_havechild) && this.b_opened ? 8 : 0) + (!b_junction && this.o_root.o_selected == this ? 4 : 0) + (b_junction ? 2 : 0) + (b_junction && this.is_last() ? 1 : 0))];
  316. }
  317. var trees = [];
  318. get_element = document.all ?
  319.     function (s_id) { return document.all[s_id] } :
  320.     function (s_id) { return document.getElementById(s_id) };
  321. var manageall=false
  322. function expand_or_collapse_all (o_tree, b_collapse) {     
  323.      manageall=true
  324.      for (var i = 1; i < o_tree.a_index.length; i++) 
  325.      {
  326.         var o_item = o_tree.a_index[i];
  327.         if( o_item.a_children.length>0 )
  328.             o_item.open(b_collapse);
  329.      }
  330.      manageall=false
  331. }
  332. function expand_or_collapse_level (o_tree, level) 
  333. {     
  334.      for (var i = 1; i < o_tree.a_index.length; i++) 
  335.      {
  336.         var o_item = o_tree.a_index[i];
  337.         if (o_item.n_depth==level && o_item.a_children.length>0 ) 
  338.             o_item.open(true);
  339.      }
  340. }
  341. //For ScriptManage by ghqian 2007-10-25 
  342. iftypeof(Sys)!="undefined" && Sys.Application) {     
  343.       Sys.Application.notifyScriptLoaded();
  344.  } 

        注:最后四行代码用于在.net里使用UpdatePanel的情况。

 

(二)定义树的图标(treeIcons.js)

            在该文件里定义了一个数组tree_tpl,描述了树的节点用什么图片来表示。在定义树的时候需要传入这个数组作为参数。

  1. var tree_tpl = {
  2.     'target'  : 'elist',    // name of the frame links will be opened in
  3.                             // other possible values are: _blank, _parent, _search, _self and _top
  4.     'icon_e'  : '../icons/empty.gif'// empty image
  5.     'icon_l'  : '../icons/line1.gif',  // vertical line
  6.     
  7.     'icon_48' : '../icons/uppost.gif',   // root icon normal
  8.     'icon_52' : '../icons/postopen.gif',   // root icon selected
  9.     'icon_56' : '../icons/uppost.gif',   // root icon opened
  10.     'icon_60' : '../icons/postopen.gif',   // root icon selected
  11.     
  12.     'icon_16' : '../icons/uppost.gif'// node icon normal
  13.     'icon_20' : '../icons/postopen.gif'// node icon selected
  14.     'icon_24' : '../icons/uppost.gif'// node icon opened
  15.     'icon_28' : '../icons/postopen.gif'// node icon selected opened
  16.     'icon_0'  : '../icons/post.gif'// leaf icon normal
  17.     'icon_4'  : '../icons/post.gif'// leaf icon selected
  18.     'icon_8'  : '../icons/post.gif'// leaf icon opened
  19.     'icon_12' : '../icons/post.gif'// leaf icon selected
  20.     
  21.     'icon_2'  : '../icons/joinbottom1.gif'// junction for leaf
  22.     'icon_3'  : '../icons/join1.gif',       // junction for last leaf
  23.     'icon_18' : '../icons/plusbottom1.gif'// junction for closed node
  24.     'icon_19' : '../icons/plus1.gif',       // junctioin for last closed node
  25.     'icon_26' : '../icons/minusbottom1.gif',// junction for opened node
  26.     'icon_27' : '../icons/minus1.gif'       // junctioin for last opended node
  27. };
  28. //For ScriptManage by Jasson Qian 2007-10-25
  29. iftypeof(Sys)!="undefined" && Sys.Application) {     
  30.       Sys.Application.notifyScriptLoaded();
  31.  } 

(三)支持C#下生成Script树节点数组的NodeDyn.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections;
  4. public sealed class NodeDyn
  5. {
  6.     public string name;
  7.     public string url;
  8.     public string data;
  9.     public bool haveChild = false;
  10.     public ArrayList childNode;
  11.     public NodeDyn parentNode = null;   //add by ghqian 2007-9-9
  12.     public NodeDyn()
  13.     {
  14.         childNode = new ArrayList();
  15.     }
  16.     public NodeDyn AddChildNode(NodeDyn cNode)
  17.     {
  18.         this.childNode.Add(cNode);
  19.         cNode.parentNode = this;    //add by ghqian 2007-9-9
  20.         return this;
  21.     }
  22.     public string GetScript(NodeDyn node)
  23.     {
  24.         string m_sFunction = "";
  25.         m_sFunction += @"<SCRIPT language='javascript'>";
  26.         m_sFunction += @"var TREE_ITEMS =[";
  27.         m_sFunction += AddItem(node).Replace(" "" ");
  28.         m_sFunction = m_sFunction.TrimEnd(",".ToCharArray());
  29.         m_sFunction += "];";
  30.         m_sFunction += @"</SCRIPT>";
  31.         return m_sFunction;
  32.     }
  33.     private string AddItem(NodeDyn node)
  34.     {
  35.         string str = "";
  36.         if (node.childNode.Count != 0)
  37.             str += "['" + node.name + "','" + node.url + "'," + node.haveChild.ToString().ToLower() + ",'" + node.data + "',";        //Add the last "," by ghqian 2007-9-1
  38.         else if( node.parentNode==null )          //add by ghqian 2007-9-9
  39.         {
  40.             str += "['" + node.name + "','" + node.url + "'," + node.haveChild.ToString().ToLower() + ",'" + node.data + "']";
  41.         }
  42.         for (int i = 0; i < node.childNode.Count; i++)
  43.         {
  44.             NodeDyn cNode = (NodeDyn)node.childNode[i];
  45.             if (cNode.childNode.Count == 0)
  46.             {
  47.                 if (i == node.childNode.Count - 1)
  48.                     str += "['" + cNode.name + "','" + cNode.url + "'," + cNode.haveChild.ToString().ToLower() + ",'" + cNode.data + "']";
  49.                 else
  50.                     str += "['" + cNode.name + "','" + cNode.url + "'," + cNode.haveChild.ToString().ToLower() + ",'" + cNode.data + "'],";
  51.             }
  52.             str += AddItem(cNode);
  53.         }
  54.         if (node.childNode.Count != 0)
  55.             str += "],";
  56.         return str;
  57.     }
  58.     /// <summary>
  59.     /// add by ghqian 2007-1-19
  60.     /// 将当前结点生成一个数组字符串,如"['name','url',true,'id']"
  61.     /// </summary>
  62.     /// <returns></returns>
  63.     public string GetString()
  64.     {
  65.         return String.Format("['{0}','{1}',{2},'{3}']"this.name, this.url, this.haveChild.ToString().ToLower(), this.data).Replace(" "" ");
  66.     }
  67. }

(四) 生成初始化就要显示的树节点的JavaScript数组并输出到HTML(示例中只显示根节点,在展开的时候自动展开到第一级)

HTML:

  1.  <%-- 在后台生成初始化树的Script代码 --%>
  2.             <asp:Literal ID="ltScript" runat="server" />       

C#的Load事件中生成要显示的节点:

  1.  protected void Page_Load(object sender, EventArgs e)
  2.         {
  3.             // 注册Ajax
  4.             AjaxPro.Utility.RegisterTypeForAjax(typeof(Default));
  5.             //创建根节点
  6.             NodeDyn root = new NodeDyn();
  7.             root.name = "Dynamical Load Tree Root";
  8.             root.data = "0";
  9.             root.haveChild = true;
  10.             // 将根节点的Script数组输出到页面: var TREE_ITEMS =[['Dynamical Load Tree Root','',true,'0']];
  11.             ltScript.Text = root.GetScript(root);
  12.         }

 

       运行后输出到页面的代码为:

  1. <SCRIPT language='javascript'>var TREE_ITEMS =[['Dynamical Load Tree Root','',true,'0']];</SCRIPT>    

(五)C#注册Ajax并注册GetChild方法

        在C#中我们需要实现一个GetChild方法(名称不一定是GetChild,前后一致即可),能够根据树节点生成该节点的子节点的数组。

        首先需要在项目中引用AjaxPro.2.dll,并且在web.config的httpHandlers节中增加

  1. <httpHandlers>
  2.             <add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2"/>
  3. </httpHandlers>

        其次在页面的Load事件中注册Ajax

                               AjaxPro.Utility.RegisterTypeForAjax(typeof(Default));

 

        然后就注册并实现GetChild方法:

  1.  [AjaxPro.AjaxMethod]
  2.         public string GetChild(string parentId)
  3.         {
  4.             StringBuilder sb = new StringBuilder();
  5.             DataRow[] drs = DtTreeData.Select(" ParentID=" + parentId);
  6.             
  7.             sb.Append("[");
  8.             for (int i = 0; i < drs.Length; i++ )
  9.             {
  10.                 NodeDyn node = GetNode(drs[i]);
  11.                 sb.Append(node.GetString());
  12.                 sb.Append(",");
  13.             }
  14.             return sb.ToString().TrimEnd(',') + "]";
  15.         }

(六)在HTML中初始化树(aspx文件中)

            首先定义一个JavaScript函数,来捕获用户点击树节点的操作

  1. // 当用户点击树节点时响应的事件
  2.                 function OnTreeItemClick( name)
  3.                 {
  4.                     document.getElementById("tdText").innerText = "Selected Item: " + name;
  5.                 }

           但学要在生成节点时将给事件注册给node.url。 我们可以在这个事件中做任何你想做的事情,例如打开新的网页等等。

           然后定义一个getChild的JavaScript函数来实现取得子节点的方法:

  1.  // 取某个节点的下级节点
  2.                 function getChild( parentId )
  3.                 {
  4.                     var items =  eval(DynLoadTree.Default.GetChild( parentId ).value);  // 通过Ajax调用后台代码
  5.                     return items;
  6.                 }

          接下来就是定义并初始化树了:

  1.  function loadTree()
  2.                 {
  3.                     if( TREE_ITEMS!=null && TREE_ITEMS.length>0 )
  4.                     {
  5.                         var my_tree = new tree (TREE_ITEMS, tree_tpl, getChild );
  6.                         expand_or_collapse_level (my_tree,0);
  7.                     }
  8.                 }
  9.                 
  10.                 //加载树
  11.                 loadTree();    

(七)其他用法:

    (1) 有时候我们需要在指定的地方显示树(例如在一个指定的<td></td>内来显示树),我们可以将loadTree()方法放到要显示树的地方来实现,另外还可以在定义tree时添加一个参数,将要显示树的容器ID传给tree:

  1.  var my_tree = new tree (TREE_ITEMS, tree_tpl, getChild, "containerId" );

   (2)通过代码来选择一个节点:

  1. my_tree.selectByData( data, runClientEvent )

     如果runClientEvent为true,则选择该节点的同时执行对应的树节点点击的客户端事件,即本示例中的OnTreeItemClick()。

      当然,treeDyn.js中还有很多函数可以使用,文件头部的几个全局变量也起了相应的控制作用。重要的是这个思路,在实际应用中可以灵活变通,不要拘泥于本示例。