How to count children from different lists? [jQuery]
I'm trying to count the number of child elements a certain category has.
This is the situation:
<ul id="select_cat">
<li id="_1">Category 1 (<span>#</span>)</li>
<li id="_2">Category 2 (<span>#</span>)</li>
</ul>
<ul id="cat_1>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li&开发者_如何学运维gt;
</ul>
<ul id="cat_2">
<li>Link 1</li>
<li>Link 2</li>
</ul>
So I want to count the number of children a category has. In this example the first cardinal sign should be 3, and the second should be 2.
How can I do this, using jQuery.
Check an example (not jQuery)
Thanks!
$('#select_cat li').each(function() {
$('span', this).text($('#cat' + this.id).children().length);
});
Example:
$("#cat_2").children("li").length
I have a feeling the question wants to ask something more.
Anyway, it's just wiring it up to some heuristic. E.g. iterate over the "select_cat" elements with each
and use their ID/position/name to count the elements in a category above and then use a text
on the span (isolated with find/child
), etc.
My two cents: I'd make the server do it.
You can do either of this:
alert($("#cat_1").children("li").length);
alert($("#cat_1").children("li").size());
$("#select_cat li").each(function(){
$("span", this).html(
$("#cat" + $(this).attr('id')).children().size();
);
});
精彩评论