Okay, if I have a html document that looks a bit like this:
<div class='item'> ... </div>
<div class='item'> ... </div>
<div class='item'> ... </div>
<div class='item'> ... </div>
I know I an iterat开发者_运维技巧e over them by doing
$('.item').each
But what if I already know I want to do something with the second one? Is there some sort of syntax similar to:
$('.item')[2]
which is usable as a selector? ie. I'd want to do:
$('.item')[2].css('display','block');
Possible or not? :)
Yup, .eq()
will restrict the jQuery set to just the one element you want:
$('.item').eq(2).css('display','block');
There is also an :eq()
selector that will do the same:
$('.item:eq(2)').css('display','block');
As Andy mentions in the comments, both of these functions use zero-based indexing... Meaning 2
is the third element...
精彩评论