jQuery ASP.NET 手风琴 event.target 错误

发布于 2024-11-11 13:39:59 字数 5692 浏览 4 评论 0原文

我一直在尝试使用 ASP.NET 学习 jQuery。我一直在关注 Bipin Joshi 的优秀文章 'http://www.codeguru.com/csharp/article.php/c18665/Developing-a-Database-Driven-Accordion-Menu-Using-WCF-and-jQuery。 htm'

我对文章代码做了一些更改:我使用的是页面方法而不是 WCF 服务;我使用 [AdventureWorksLT].[SalesLT].[ProductCategory] ​​表来构建菜单和菜单项。

正在显示菜单,但当我单击菜单时,不会显示菜单项。我收到以下几行错误:

$(event.target).children().remove(); -- 删除用户单击的菜单的所有子元素。

$(event.target).append(html); -- 它将 MenuItems HTML 片段附加到用户单击的菜单中。

在函数 OnMenuClick(event) 中,

我收到错误“event.target 未定义”。

我做错了什么?我错过了什么吗?有没有更简单的方法来做到这一点?

这是我的代码:

我的 ASP.NET 页面正文中有一个 id="accordionContainer" 的“div”。

    $(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);
                }
            })
    } 

在代码后面:

[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;
        }
    }
}

提前致谢。

亲切的问候

沃尔特

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="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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜`诱少女 2024-11-18 13:39:59

您的 onclick 正在调用 OnMenuClick 并传入一个对象,并且该对象不是事件,因此没有 target 属性。

如果这是我的代码,我会使用事件委托这样编写。这是使用 jQuery 1.6;如果您使用的是不同版本,请告诉我,我将对此代码进行更改以支持您的版本:

(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);
                    }
                }
            });
        });
});

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);
                    }
                }
            });
        });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文