Javascript树型菜单(含源码)

看到园友发表了一篇关于JS树的文章,看了之后,觉得应该可以精简不少代码,

想到了以前做的项目里面用到了一个JS树,于是试着修改了一下,现把代码贴出来与大家共享,还请大家多扔砖头!

前端代码:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">



<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title></title>

    <link href="images/Tree/Tree.css" rel="stylesheet" type="text/css" />

    <style type="text/css">

        #tabMenu {

            border: 1px solid #A3C0E8;

            position: absolute;

            opacity: 0.9;

            display: none;

            cursor: pointer;

            border-collapse: collapse;

            z-index:9999;

            background-color:#fff;

        }

        #tabMenu td {

            border: 1px solid #A3C0E8;

            height: 30px;

            width: 120px;

            text-align: center;

        }

        .righText {

            text-align:right;

            width:120px;

            height:30px;

        }

        #tabDepartment td {

            border: 1px solid #A3C0E8;

        }

    </style>

    <script src="js/jquery-1.11.1.js" type="text/javascript"></script>

    <script src="js/Tree.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(function() {

           

            reload();



            var dt = document.getElementById("Tree");

            dt.oncontextmenu = function() {

                return false;

            }

            document.onclick = function() {

                $("#tabMenu").css("display", "none");

            }

            $("#tabMenu").mouseleave(function() {

                $(this).css("display", "none");

            });

        });



        function reload() {

            $.ajax({

                type: 'POST',

                url: "Default.aspx/GetData2",

                data: "{ pid: 0 }",

                contentType: "application/json;charset=utf-8",

                dataType: "json",

                success: function(data) {

                    var obj = eval('(' + data.d + ')');

                    if (obj) {

                        var tree = new treeview("treeview", "/Images/Tree", false, false);

                        var dt = document.getElementById("Tree");

                        dt.innerHTML = "";

                        loopNode(obj, tree);

                        tree.create(dt);

                        tree.nodes.items[0].expand();

                    }

                },

                error: function(r, ex) {

                     

                }

            });

        }

        function stopBubble(e) {

            if (e && e.stopPropagation)

                e.stopPropagation();

            else

                window.event.cancelBubble = true;

            return false;

        }

        function loopNode(obj, parNode) {

            var nd = new node(obj.Name, obj.Name, "", obj.PID, obj.ID, false);

            parNode.add(nd);

            var len = obj.Child.length;

            if (len > 0) {

                for (var i = 0; i < len; i++) {

                    var d = obj.Child[i];

                    if (d.Child && d.Child.length > 0) {

                        loopNode(d, nd)

                    }

                    else {

                        nd.add(new node(d.Name, d.Name, "", d.PID, d.ID, false));

                    }

                }

            }

        }

        treeview.prototype.oncontextmenu = function(sender, e) {

            selectedNode = sender;

            var ps = sender.position(e);

            $("#tabMenu").css({ left: ps.x, top: ps.y, display: 'block' });

            return stopBubble(e);

        }

        treeview.prototype.onnodeclick = function(sender) {

            selectedNode = sender;

           

            return false;

        }

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <div id="Tree">

    

    </div>

    

        <table id="tabMenu" border="1">

        <tr>

            <td>添加</td>

        </tr>

        <tr>

            <td>修改</td>

        </tr>

        <tr>

            <td>删除</td>

        </tr>

    </table>

    </form>

</body>

</html>

 

后台代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Services;

using System.Text;

using Utility;

using Newtonsoft.Json;



namespace WebApplication1

{

    public partial class Default : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {



        }



        [WebMethod]

        public static string GetData2(int pid)

        {

            StringBuilder sb = new StringBuilder();

            List<HRDepartmentEntity> alist = Getlist();

            List<HRDepartmentEntity> clist = alist.FindAll(p => p.ParentID == pid).OrderBy(q => q.DepartmentOrder).ToList();

          

            LoopDepartment(alist, clist, sb, pid);

            

            return sb.ToString();

        }



        [WebMethod]

        public static string GetData(int pid)

        {

            StringBuilder sb = new StringBuilder();

            List<HRDepartmentEntity> alist = Getlist();

            DepartmentSingle ds = new DepartmentSingle();

            ds.Name = "Test";

            LoopDepartment2(alist, ds);

            string str = JsonConvert.SerializeObject(ds);

            return str;

        }





        /// <summary>

        /// 得到组织架构列表

        /// </summary>

        /// <returns></returns>

        private static List<HRDepartmentEntity> Getlist()

        {

            return SQLServerHelper.ExecuteDataTable("select * from HR_Department").ToList<HRDepartmentEntity>();

        }



        private static void LoopDepartment2(List<HRDepartmentEntity> list1, DepartmentSingle ds)

        {

            List<HRDepartmentEntity> list2 = list1.FindAll(p => p.ParentID == ds.ID).OrderBy(q => q.DepartmentOrder).ToList();

            if (list2.Count > 0)

            {

                ds.Child = list2.ConvertAll<DepartmentSingle>(p => new DepartmentSingle { ID = p.DepartmentID, PID = p.ParentID, Name = p.DepartmentName });

                foreach (DepartmentSingle ds2 in ds.Child)

                {

                    LoopDepartment2(list1, ds2);

                }

            }

        }



        private static void LoopDepartment(List<HRDepartmentEntity> alist, List<HRDepartmentEntity> clist, StringBuilder sb, int pid)

        {

            for (int i = 0; i < clist.Count; i++)

            {

                HRDepartmentEntity entity = clist[i];

                int id = entity.DepartmentID;

                List<HRDepartmentEntity> list2 = alist.FindAll(p => p.ParentID == id).OrderBy(q => q.DepartmentOrder).ToList();

                sb.Append("{" + string.Format("ID:{0},PID:{1},Name:'{2}',Order:{3},Child:", id, entity.ParentID, entity.DepartmentName, entity.DepartmentOrder) + "[");

                if (list2.Count > 0)

                {

                    LoopDepartment(alist, list2, sb, id);

                }

                if (i < clist.Count - 1)

                {

                    sb.Append("]},");

                }

                else

                {

                    sb.Append("]}");

                }

            }

        }

    }



    /// <summary>

    /// 组织架构实体类

    /// </summary>

    public class HRDepartmentEntity

    {



        #region 私有变量

        private Int32 m_DepartmentID;

        private String m_DepartmentName;

        private Int32 m_ParentID;

        private String m_ParentName;

        private String m_DepartmentIcon;

        private String m_ResponsiblePerson;

        private String m_Tel;

        private String m_Email;

        private String m_Description;

        private Int32 m_DepartmentOrder;

        private Int32 m_IsDelete;

        private DateTime m_DeleteTime;

        #endregion



        # region 属性方法



        public Int32 DepartmentID

        {

            get { return m_DepartmentID; }

            set { m_DepartmentID = value; }

        }



        public String DepartmentName

        {

            get

            {

                return m_DepartmentName;

            }

            set { m_DepartmentName = value; }

        }



        public Int32 ParentID

        {

            get { return m_ParentID; }

            set { m_ParentID = value; }

        }



        public String ParentName

        {

            get

            {

                return m_ParentName;

            }

            set { m_ParentName = value; }

        }



        public String DepartmentIcon

        {

            get

            {

                return m_DepartmentIcon;

            }

            set { m_DepartmentIcon = value; }

        }



        public String ResponsiblePerson

        {

            get

            {

                return m_ResponsiblePerson;

            }

            set { m_ResponsiblePerson = value; }

        }



        public String Tel

        {

            get

            {

                return m_Tel;

            }

            set { m_Tel = value; }

        }



        public String Email

        {

            get

            {

                return m_Email;

            }

            set { m_Email = value; }

        }



        public String Description

        {

            get

            {

                return m_Description;

            }

            set { m_Description = value; }

        }



        public Int32 DepartmentOrder

        {

            get

            {

                return m_DepartmentOrder;

            }

            set { m_DepartmentOrder = value; }

        }



        public Int32 IsDelete

        {

            get

            {

                return m_IsDelete;

            }

            set { m_IsDelete = value; }

        }



        public DateTime DeleteTime

        {

            get

            {

                return m_DeleteTime;

            }

            set { m_DeleteTime = value; }

        }

        #endregion

    }



    public class DepartmentSingle

    {

        public int ID;

        public int PID;

        public string Name;

        public List<DepartmentSingle> Child;

    }

}


ok了~~就这些,完整源代码下载

 

 

 

 

你可能感兴趣的:(JavaScript)