Given the following example table:
<ul class="topnav">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
What are the differences between:
$selector1 = $('ul.topnav > li');
a开发者_开发问答nd
$selector2 = $('ul.topnav').each();
EDIT:
$selector2 = $('ul.topnav li').each();
The first will contain all li
's which are a direct child of ul.topnav
, the second will contain all ul.topnav
elements.
$('ul.topnav > li')
will select all <li>
s directly under the ul
.
each
should take a function as a parameter, and iterate over all matched <ul>
- it doesn't not take the children <li>
s. If anything, you want $('ul.topnav').children()
, which is identical if the ul
only contains li
elements anyway.
For example, this will alert
the number of children each list has (in your case, only the number 3
)
$selector2 = $('ul.topnav').each(function(){
alert($(this).children().length);
});
Also see the jquery API.
The second one will evaluate them individually, whereas the first one will evaluate them as a group
精彩评论