Я пытался изучить jQuery с помощью ASP.NET.Я следил за прекрасной статьей Бипина Джоши 'http://www.codeguru.com/csharp/article.php/c18665/Developing-a-Database-Driven-Accordion-Menu-Using-WCF-and-jQuery.htm'
. Я внес некоторые изменения в код статьи: я использую методы страницы, а не службу WCF;Я использую таблицу [AdventureWorksLT]. [SalesLT]. [ProductCategory] для создания элементов Menu и MenuItem.
Отображаются меню, но когда я щелкаю по меню, элементы меню не отображаются.Я получаю сообщение об ошибке со следующими строками:
$ (event.target) .children (). Remove ();- удаляет все дочерние элементы меню, по которым пользователь щелкнул.
$ (event.target) .append (html);- который добавляет HTML-фрагмент MenuItems в меню, выбранное пользователем.
в функции OnMenuClick (событие)
Я получаю сообщение об ошибке «event.target is undefined».
Что я делаю не так?Я что-то пропустил?Есть ли более простой способ сделать это?
Вот мой код:
У меня есть 'div' с id = "accordionContainer" в теле моей страницы ASP.NET.
$(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;
}
}
}
Заранее спасибо.
С уважением
Вальтер