我一直在尝试使用ASP.NET学习jQuery。我一直在关注Bipin Joshi'http://www.codeguru.com/csharp/article.php/c18665/Developing-a-Database-Driven-Accordion-Menu-Using-WCF-and-jQuery.htm'
的优秀文章我对文章代码做了一些更改:我使用的是Page Methods而不是WCF服务;我正在使用[AdventureWorksLT]。[SalesLT]。[ProductCategory]表来构建Menu和MenuItems。
正在显示菜单,但是当我单击菜单时,不显示MenuItems。我收到的错误如下:
$(event.target)。儿童()除去(); - 删除用户点击的菜单的所有子元素。
$(event.target).append(HTML); - 将MenuItems HTML片段附加到用户点击的菜单。
在函数OnMenuClick(事件)
我收到错误'event.target is undefined'。
我做错了什么?我错过了什么吗?有更简单的方法吗?
这是我的代码:
我的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;
}
}
}
提前致谢。
亲切的问候
沃尔特
答案 0 :(得分:1)
你正在onclick调用OnMenuClick并传入一个对象,并且该对象不是一个事件,因此没有目标属性。
如果这是我的代码,我会像使用事件委托一样编写代码。这是使用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);
}
}
});
});
});