首先,寫這篇文章的目的,在于幫助更多人更加輕松地實(shí)現(xiàn)客戶端Treeview,程序員的時(shí)間是寶貴的,在客戶端,你可能只需要幾行代碼就能完全搞定這棵樹。 EasyUI易用靈活,但可惜說明文檔太簡單,網(wǎng)上不少的一些所謂異步樹,名為異步,實(shí)則是一次性加載了全部的樹內(nèi)容,這樣在構(gòu)建一棵比較大的樹的時(shí)候,可能會造成效率上的嚴(yán)重影響. 我們的目標(biāo),一般是:點(diǎn)擊某節(jié)點(diǎn)前的"展開"圖標(biāo)====加載該節(jié)點(diǎn)下的子節(jié)點(diǎn)====下次展開,不用加載,直接展開;點(diǎn)擊節(jié)點(diǎn)的文字,選定內(nèi)容,做我們所要做的事情.效果如下圖: 于是行動開始,首先,我們要加載EasyUI的核心文件及資源文件,HTML具體代碼如下---
![]() 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 3 <html xmlns="http://www./1999/xhtml" > 4 <head runat="server"> 5 <title>Untitled Page</title> 6 <link rel="stylesheet" href="easyui/themes/default/easyui.css" /> 7 <link rel="stylesheet" href="easyui/themes/icon.css" /> 8 <script type="text/javascript" src="easyui/jquery-1.4.2.min.js"></script> 9 <script type="text/javascript" src="easyui/jquery.easyui.min.js"></script> 10 <script type="text/javascript"> 11 12 $(function(){ 13 $('#tt2').tree({ 14 checkbox: false, 15 url: '/common/GetGoupJsonByPid.ashx?pid=0', 16 onBeforeExpand:function(node,param){ 17 $('#tt2').tree('options').url = "/common/GetGoupJsonByPid.ashx?pid=" + node.id;// change the url 18 //param.myattr = 'test'; // or change request parameter 19 }, 20 onClick:function(node){ 21 alert(node.id); 22 } 23 }); 24 }); 25 </script> 26 </head> 27 <body> 28 <form id="form1" runat="server"> 29 <div style="width:150px;"> 30 <ul id="tt2"> 31 </ul> 32 </div> 33 </form> 34 </body> 35 </html>
大家可以看到,這個代碼已經(jīng)是相當(dāng)簡單了,然后, 我們要做的是服務(wù)器端的代碼返回工作,其實(shí)也很簡單,核心代碼如下:
![]() 1 int parentId = -1;//默認(rèn)為-1,如果請求參數(shù)不正確,將不返回任何值 2 string resultStr = string.Empty; 3 if (!string.IsNullOrEmpty(context.Request.QueryString["pid"])) 4 { 5 Int32.TryParse(context.Request.QueryString["pid"], out parentId); 6 } 7 if (parentId >= 0) 8 { 9 ........//此處省略得到數(shù)據(jù)列表的代碼 10 resultStr = ""; 11 resultStr += "["; 12 foreach (數(shù)據(jù)類 item in 數(shù)據(jù)集List<>) 13 { 14 resultStr += "{"; 15 resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"iconCls\": \"icon-ok\", \"state\": \"closed\"", item.Id.ToString(), item.TxtName); 16 resultStr += "},"; 17 } 18 resultStr = resultStr.Substring(0, resultStr.Length - 1); 19 resultStr += "]"; 20 } 21 22 23 //最后返回json數(shù)據(jù) 24 context.Response.Write(resultStr); 25
請注意,以上的服務(wù)器端代碼,請根據(jù)具體數(shù)據(jù)結(jié)構(gòu)情況進(jìn)行修改.
好了,這樣,我們的工作就完成了.是不是很簡單(另一個更簡單,更好的Tree插件jquery.simple.tree).具體實(shí)現(xiàn)中,還可以根據(jù)情況進(jìn)行多選的設(shè)置. EasyUI代碼下載"http://jquery-easyui./download",我這里用的版本是1.2 如果哪位兄弟用了覺得OK,可以留言,我們一起探討. |
|