开发者

jQuery ASP.NET Accordion event.target Error

开发者 https://www.devze.com 2023-03-09 18:09 出处:网络
I have been trying to learn jQuery using ASP.NET.I have been following the excellent article by Bipin Joshi \'http://www.codeguru.com/csharp/article.php/c18665/Developing-a-Database-Driven-Accordion-M

I have been trying to learn jQuery using ASP.NET. I have been following the excellent article by Bipin Joshi 'http://www.codeguru.com/csharp/article.php/c18665/Developing-a-Database-Driven-Accordion-Menu-Using-WCF-and-jQuery.htm'

I have made some changes to the article code: I'm using Page Methods and not a WCF Service; I'm using the [AdventureWorksLT].[SalesLT].[ProductCategory] table to build the Menu and MenuItems.

The Menus are being displayed but when I click on a Menu the MenuItems are not displayed. I am receiving an error with the following lines:

$(event.target).children().remove(); -- which removes all the child elements of the Menu that has been clicked by the user.

$(event.target).append(html); -- which appends the MenuItems HTML fragment to the Menu clicked by the user.

in function OnMenuClick(event)

I'm getting the error 'event.target is undefined'.

What am I doing wrong? Am I missing something? Is there an easier way to do this?

Here is my code:

I have a 'div' with id开发者_如何学Go="accordionContainer" in the body of my ASP.NET page.

    $(document).ready(function () {
        $('#accordionContainer').html('Loading...')
        $.ajax({
            type: "POST",
            contentType: "application/json",
            data: "{}",
            url: "Catalogue.aspx/GetMenus",
            dataType: "json",
            success: function (response) {
                if (response != null && response.d != null) {
                    CreateMenus(response.d);
                }
            }
        });
    });

    function CreateMenus(results) {
        $("#accordionContainer").empty();
        var _html = '';
        for (var i = 0; i < results.length; i++) {
            //_html += '<div class="Menu" onclick="OnMenuClick(' + results[i].MenuID + ');">' + results[i].Text + '</div>';
            _html += '<div class="Menu" onclick="OnMenuClick({ MenuID: ' + results[i].MenuID + '});">' + results[i].Text + '</div>';
        }
        document.getElementById('accordionContainer').innerHTML = _html;
    }

    //function OnMenuClick(MenuID) {
    function OnMenuClick(event) {
        $("div[id ^= 'menuItemGroup']").slideUp(500);
        $.ajax(
            {
                type: "POST",
                contentType: "application/json",
                data: "{'MenuID':'" + event.MenuID + "'}",
                url: "Catalogue.aspx/GetMenuItems",
                dataType: "json",
                success: function (items) {
                    $(event.target).children().remove();
                    var html = "<div id='menuItemGroup" + event.MenuID + "' style='display:none'>";
                    for (var j = 0; j < items.d.length; j++) {
                        html += "<div class='MenuItem'><a href='#' onclick='GetProducts(" + items.d[j].MenuItemID + ");'>" + items.d[j].Text + "</a></div>";
                    }
                    html += "</div>";
                    $(event.target).append(html);
                    $("#menuItemGroup" + event.MenuID).slideDown(500);
                },
                error: function (err) {
                    alert(err.status + " - " + err.statusText);
                }
            })
    } 

In code behind:

[Serializable]
public class Menu
{
    public int MenuID { get; set; }
    public string Text { get; set; }
}
[System.Web.Services.WebMethod]
public static List<Menu> GetMenus()
{
    List<Menu> myMenus = new List<Menu>();

    using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["AdventureWorksLTConnectionString"].ConnectionString))
    {
        // Fetch Menus from AdventureWorksLT database.
        string sqlString = "SELECT [ProductCategoryID],[ParentProductCategoryID],[Name] FROM [SalesLT].[ProductCategory] WHERE [ParentProductCategoryID] IS NULL";
        using (SqlCommand cmd = new SqlCommand(sqlString, conn))
        {
            conn.Open();

            SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            while (rdr.Read())
            {
                Menu m = new Menu();
                m.MenuID = Convert.ToInt32(rdr["ProductCategoryID"]);
                m.Text = rdr["Name"].ToString();
                myMenus.Add(m);
            }

            conn.Close();

            return myMenus;
        }
    }
}
[Serializable]
public class MenuItem
{
    public int MenuID { get; set; }
    public int MenuItemID { get; set; }
    public string Text { get; set; }
}
[System.Web.Services.WebMethod]
public static List<MenuItem> GetMenuItems(int MenuID)
{
    List<MenuItem> myMenuItems = new List<MenuItem>();

    using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["AdventureWorksLTConnectionString"].ConnectionString))
    {
        // Fetch Products from AdventureWorksLT database.
        string sqlString = "SELECT [ProductCategoryID],[ParentProductCategoryID],[Name] FROM [SalesLT].[ProductCategory] WHERE [ParentProductCategoryID]=@MenuID";

        using (SqlCommand cmd = new SqlCommand(sqlString, conn))
        {
            SqlParameter paramMenuID = new SqlParameter("@MenuID", SqlDbType.Int);
            paramMenuID.Value = MenuID;
            cmd.Parameters.Add(paramMenuID);

            conn.Open();

            SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            while (rdr.Read())
            {
                MenuItem mi = new MenuItem();
                mi.MenuID = Convert.ToInt32(rdr["ParentProductCategoryID"]);
                mi.MenuItemID = Convert.ToInt32(rdr["ProductCategoryID"]);
                mi.Text = rdr["Name"].ToString();
                myMenuItems.Add(mi);
            }

            conn.Close();

            return myMenuItems;
        }
    }
}

Thanks in advance.

Kind Regards

Walter


You're onclick is calling OnMenuClick and passing in an object, and the object is not an event, so there is no target property.

If this were my code, I would write it like so using event delegation. This is using jQuery 1.6; let me know if you are using a different version and I will make the changes to this code to support your version:

(function() {
    var accordion = $("#accordionContainer");

    var createMenus = function(results) {
        var stringBuilder = [];

        accordion.empty();

        for (var i = 0, len = results.length; i < len; i++) {
            stringBuilder.push('<div class="menu" data-menu-id="'+ results[i].MenuId +'">' + results[i].Text + '</div>');
        }

        accordion.html(stringBuilder.join(''));
    };

    var menuClick = function(e) {
        var element = $(this),
            menuId = element.data('menuId');

        $("div[id^='menuItemGroup']").slideUp(500);

        $.ajax({
            type: "POST",
            contentType: "application/json",
            data: { MenuID: element.data('menuId') },
            url: "Catalogue.aspx/GetMenuItems",
            dataType: "json",
            success: function (items) {
                var stringBuilder = [],
                    currentItem;

                stringBuilder.push("<div id='menuItemGroup" + event.MenuID + "' style='display:none'>");

                for (var i = 0, len = items.d.length; i < len; i++) {
                    currentItem = item.d[i];

                    stringBuilder.push("<div class='menu-item'><a href='#' data-menu-item-id='" + currentItem.MenuItemID + "'>" + currentItem.Text + "</a></div>");
                }

                stringBuilder.push("</div>");

                element.html(stringBuilder.join(''));

                $("#menuItemGroup" + event.MenuID).slideDown(500);
            },
            error: function (err) {
                alert(err.status + " - " + err.statusText);
            }
        });
    };  

    $(document)
        .delegate('.menu', 'click', menuClick)
        .delegate('.menu-item', click, GetProducts)
        .ready(function() {
            accordion.html('Loading...');

            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: "Catalogue.aspx/GetMenus",
                dataType: "json",
                success: function (response) {
                    if (response && response.d) {
                        createMenus(response.d);
                    }
                }
            });
        });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消