首页 > 代码库 > 动态获取导航栏

动态获取导航栏

这里记录的是两层的导航栏。首先数据库中建两张表,一张存储父节点数据,另一张存储子节点数据,结构如下

父表:

技术分享

子表:

技术分享

这里有两种方式实现导航栏。第一种,通过两个Repeater循环得到并展示导航栏。第二种,通过拼json方式传给前台,前台动态拼html得到导航栏。

首先记录第一种方法:

技术分享
  protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Repeater1.DataSource = getfather();
                Repeater1.DataBind();

            }
        }

        protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            RepeaterItem item = e.Item;
            DataRowView drv = (DataRowView)item.DataItem;
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater rpt = (Repeater)item.FindControl("rep");
                string categoryId = Convert.ToString(drv.Row["CategoryNumber"]);
                if (categoryId != null)
                {
                    rpt.DataSource = getson(categoryId);
                    rpt.DataBind();

                }
            }
        }

        private DataTable getfather()
        {
            string sql = "select * from T_ClothCategory";
            return SqlHelper.ExecuteDataTable(sql);
        }

        private DataTable getson(string id)
        {
            string sql = "select * from T_Clothes where categoryId=" + id;
            return SqlHelper.ExecuteDataTable(sql);
 
        }
View Code

此方法通过后台取得数据,在Repeater1_ItemDataBound绑定项中给repeater填加数据
前台

技术分享
    <script>
        $(function () {

            $(".level1 > a").click(function () {
                //$(this).addClass("current")   //给当前元素添加"current"样式
                //.next().show(500)                //下一个元素显示
                //.parent().siblings().children("a").removeClass("current")        //父元素的兄弟元素的子元素<a>移除"current"样式
                //.next().hide(500);                //它们的下一个元素隐藏
                //return false;

                $(this).addClass("current")
                .next().toggle(500)
                .parent().siblings().children("a").removeClass("current")
                .next().hide(500);
                return false;


            });
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div class="box">
                <ul class="menu">
                    <asp:Repeater ID="Repeater1" runat="server"
                        OnItemDataBound="Repeater1_ItemDataBound">
                        <ItemTemplate>
                            <li class=‘level1‘><a href=‘#‘><%#Eval("CategoryName") %></a>
                                <ul class=‘level2‘>
                                    <asp:Repeater ID="rep" runat="server">
                                        <ItemTemplate>
                                            <li><a href=‘<%# Eval("url") %>‘><%#Eval("Name")%></a>
                                        </ItemTemplate>
                                    </asp:Repeater>
                                </ul>
                            </li>
                        </ItemTemplate>
                    </asp:Repeater>

                </ul>
            </div>
        </div>
    </form>
</body>
</html>
View Code

第二种方法:

在html中dom元素加载完执行异步方法,到一般处理程序中得到数据
一般处理程序:

技术分享
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";     

            string data = http://www.mamicode.com/"select * from  dbo.T_ClothCategory";
            DataTable dtFather = SqlHelper.ExecuteDataTable(data);

            string json= convert(dtFather);

            context.Response.Write(json);
        }


        public string convert(DataTable dt)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"dongdong\":[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append("{");
                sb.Append("\"categoryName\":" +"\""+dt.Rows[i]["CategoryName"] +"\""+ ",");
                sb.Append("\"son\":[");
                int categoryNumber = Convert.ToInt32(dt.Rows[i]["CategoryNumber"]);
                DataTable dtSon = SqlHelper.ExecuteDataTable("select * from dbo.T_Clothes where categoryId=" + categoryNumber);
                for (int j = 0; j < dtSon.Rows.Count; j++)
                {
                    sb.Append("{");
                    sb.Append("\"Name\":" +"\""+dtSon.Rows[j]["Name"]+"\""+",");
                    sb.Append("\"url\":" +"\""+ dtSon.Rows[j]["url"].ToString().Trim()+"\"");
                    sb.Append("},");
                }
                sb.Remove(sb.ToString().LastIndexOf(,), 1);
                sb.Append("]},");

            }
            sb.Remove(sb.ToString().LastIndexOf(,), 1);
            sb.Append("]}");
            return sb.ToString();
        }
View Code

前台页面拼html

技术分享
    <script>
        $(function () {
            var $load = $("#loading"); 

            ////首先生成列表
            $.ajax({
                url: "GetClothes.ashx",
                type: "post",
                dataType: "json",
                beforeSend: function () {
                    $load.show();
                },
                complete: function (xhr) {
                    $load.hide();
                },
                success: function (returnData) {
                    Create(returnData.dongdong);
                }
            })

            $(document).delegate(".level1", "click", function () {
                //alert($(this).children().html());
                $(this).children("a").addClass("current")
                   .next().toggle(500)
                   .parent().siblings().children("a").removeClass("current")
                   .next().hide(500);
            })


            function Create(returnData) {
                var $ul = $("ul.menu");
                $.each(returnData, function (index, result) {
                    var li = "<li class=‘level1‘><a href=http://www.mamicode.com/‘#‘>" + result.categoryName + "</a><ul class=‘level2‘></ul></li>";
                    $ul.append(li);
                    var $sonUl = $("ul.menu > li").eq(index).find("ul");
                    $.each(result.son, function (i, data) {
                        $sonUl.append("<li><a href=http://www.mamicode.com/‘"+data.url+"‘>" + data.Name + "</a></li>");
                    })
                    console.log($ul.html());
                })
            }
        })
    </script>
</head>
<body>
    <div class="box">
        <ul class="menu"></ul>
    </div>
    <div id="loading">加载中……</div>
</body>
</html>
View Code

其中遇到的问题是,动态生成的dom元素,点击事件没有效果,网上查资料中称,要在on或者delegate事件中写方法,才会触发新生成的html的事件效果。
用到的前台css样式:

技术分享
/* reset */
body{margin:0;padding:0 0 12px 0;font-size:12px;line-height:22px;font-family:"\5b8b\4f53","Arial Narrow";background:#fff;}
form,ul,li,p,h1,h2,h3,h4,h5,h6{margin:0;padding:0;}
input,select{font-size:12px;line-height:16px;}
img{border:0;}
ul,li{list-style-type:none;}
a {color:#00007F;text-decoration:none;}
a:hover {color:#bd0a01;text-decoration:underline;}

.box {
    width: 150px;
    margin: 0 auto;
}
.menu{
    overflow:hidden;
    border-color: #C4D5DF;
    border-style: solid;
    border-width: 0 1px 1px;
}
/* lv1 */
.menu li.level1 a{
    display: block;
    height: 28px;
    line-height: 28px;
    background:#EBF3F8;
    font-weight:700;
    color: #5893B7;
    text-indent: 14px;
    border-top: 1px solid #C4D5DF;
}
.menu li.level1 a:hover{text-decoration:none;}
.menu li.level1 a.current{background:#B1D7EF;}
/* lv2 */
.menu li ul{overflow:hidden;}
.menu li ul.level2{display:none;}
.menu li ul.level2 li a{
    display: block;
    height: 28px;
    line-height: 28px;
    background:#ffffff;
    font-weight:400;
    color: #42556B;
    text-indent: 18px;
    border-top: 0px solid #ffffff;
    overflow: hidden;
}
.menu li ul.level2 li a:hover{
    color:#f60;
}

整个页面的CSS
View Code

最终效果如下
技术分享

 

动态获取导航栏