本文實例講述了jstree創建無限分級樹的方法。分享給大家供大家參考,具體如下:
首先來看一下效果
頁面加載之初
節點全部展開後
首先數據庫的表結構如下
其中Id為主鍵,PId為關聯到自身的外鍵
兩個字段均為GUID形式
層級關系主要靠這兩個字段維護
其次需要有一個類型
public class MenuType { public Guid Id { get; set; } public Guid PId { get; set; } public string MenuName { get; set; } public string Url { get; set; } public int OrderNum { get; set; } public int SonCount { get; set; } }
此類型比數據庫表增加了一個屬性
SonCount
這個屬性用來記錄當前節點的子節點的個數
注意:也可以把此屬性放在數據庫中,性能上會提升一些,但需要增加額外的代碼來維護此字段
接下來看一下取數據的方式
protected void Page_Load(object sender, EventArgs e) { if (Request["Action"] == "AJAX") { var result = GetMenu(Request["pid"]); JavaScriptSerializer serializer = new JavaScriptSerializer(); string sRet = serializer.Serialize(result); Response.Write(sRet); Response.End(); } }
頁面加載之初判斷是否需要獲取菜單數據
其中請求參數pid為客戶端需要獲取的節點ID
如果請求頂級節點,則此參數的值為00000000-0000-0000-0000-000000000000
GetMenu函數獲取需要請求的節點數據
private List<MenuType> GetMenu(string pid) { var result = new List<MenuType>(); SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=SHU;User ID=sa;Password=allen;"); conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "select a.*,b.cout as count from Menu a left join (select COUNT(*) as cout,Menu.PId from Menu group by Menu.PId) as b on a.Id = b.PId where a.PId = '" + pid + "' order by OrderNum"; SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (dr.Read()) { var obj = new MenuType(); obj.Id =Guid.Parse(dr["Id"].ToString()); obj.MenuName = dr["MenuName"].ToString(); obj.OrderNum = Convert.ToInt32(dr["OrderNum"]); obj.PId = dr["PId"] == DBNull.Value ? Guid.Empty : Guid.Parse(dr["PId"].ToString()); obj.Url = dr["Url"].ToString(); obj.SonCount = dr["count"] == DBNull.Value ? 0 : Convert.ToInt32(dr["count"]); result.Add(obj); } return result; }
在本DEMO中使用JavaScriptSerializer來序列化菜單數組
前台的代碼如下
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> <link href="Scripts/themes/default/style.css" rel="stylesheet" type="text/css" /> <script src="Scripts/jquery.js" type="text/javascript"></script> <script src="Scripts/jquery.jstree.js" type="text/javascript"></script> <script> $(function () { $.getJSON("/default.aspx?ACTION=AJAX&pid=00000000-0000-0000-0000-000000000000", function (result) { $.each(result, function (i, item) { var typeN = item.SonCount > 0 ? "jstree-closed" : "jstree-leaf"; $("#tree").append("<li id='phtml_" + item.Id + "' class='" + typeN + "'><a href='#'>" + item.MenuName + "</a></li>"); }); $("#demo2").jstree({ "plugins": ["themes", "html_data", 'types', "ui", "checkbox"], 'core': { 'animation': 0 }, "types": { "types": { "person": { "icon": { "image": "/Scripts/themes/default/person.png"} }, "depar2": { "icon": { "image": "/Scripts/themes/default/depar2.png"} }, "default": { "icon": { "image": "/Scripts/themes/default/depar1.png"} } } } }).bind("open_node.jstree", function (e, data) { var id = data.rslt.obj[0].id; if ($("#" + id + " li").length > 0) { return; } $.getJSON("/default.aspx?ACTION=AJAX&pid=" + id.replace("phtml_", ""), function (result) { var str = "<ul>" $.each(result, function (i, item) { var typeN = item.SonCount > 0 ? "jstree-closed" : "jstree-leaf"; var icon = item.SonCount > 0 ? "depar2" : "person"; str += "<li rel = '" + icon + "' id='phtml_" + item.Id + "' class='" + typeN + "'><a href='#'> " + item.MenuName + "</a></li>"; }); str += "</ul>"; $("#" + id).append(str); var tree = jQuery.jstree._reference("#" + id); tree.refresh(); $("ins[class='jstree-checkbox jstree-icon']").removeClass("jstree-icon"); $(".jstree-checkbox").attr("style", ""); }); }); }); }); </script> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <div id="demo2"> <ul id="tree"> </ul> </div> </asp:Content>
頁面加載之初,先請求頂級節點
如果頂級節點的SonCount屬性大於0
則使節點為閉合狀態(樣式為jstree-closed)
如果節點無子節點
則該節點的樣式為jstree-leaf
當用戶點擊閉合狀態的節點時,客戶端發起請求
並把點擊節點的ID傳給後端,後端獲取到點擊節點的子節點後
通過append添加到點擊節點下
至此,無限分級的樹創建完成
其中不包含數據庫
更多關於JavaScript相關內容感興趣的讀者可查看本站專題:《javascript面向對象入門教程》、《JavaScript遍歷算法與技巧總結》、《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。