jQuery Selector.size() keeps returning zero
I am building an ASP.NET MVC web application and I'm using jQuery for some client side programming. I have a category display that gets its data from the database and is dynamically generated on the client side.
When I try to hide the sub-categories in an attempt to create some sort of a customized accordion menu, nothing happens. When debugging I'm trying to alert out the size of the categories collection, and I keep getting zero although everything is being displayed on the screen the way it should. Here's the code:
//markup (my view-engine is Razor)
<div class="sharwe-categories">
<ul class="menu menu-vertical menu-accordion">
@foreach(var topLevel in Model.Categories)
{
<li class="topLevel">
<h3>
<a href="#" class="main">@topLevel.Name</a>
<a href="#" class="drop-down"></a>
</h3>
<ul class="childCategories">
@foreach (var childCategory in topLevel.Children)
{
<li><a href="#">@childCategory.Name</a></li>
}
</ul>
</li>
}
</ul>
</div>
//Javascript code:
$(document).ready(function () {开发者_StackOverflow中文版
var $categories = $('#sharwe-categories .menu li.topLevel');
var $categories_children = $('ul.childCategories', $categories).hide();
var $categories_dropdown = $('a.drop-down', $categories);
});
To be honest, I was never good with jQuery and it always pisses me off because I feel it's "unpredictable" - well maybe because I prefer working on the back-end stuff instead.
Any help would be much appreciated.
<div class="sharwe-categories">
$('#sharwe-categories .menu li.topLevel');
You've got class on div, but trying to find it by # (id). $('.sharwe-categories .menu li.topLevel');
Working with jquery might feel unpredictable when you are starting and don't know javascript limitations (like trying to detect element size while it is not inserted in DOM), but eventually you will discover that jQuery actually solves all your cross-browser javascript problems (and much more).
Quite misleading title by the way :)
精彩评论