开发者

access a single object in a returned collection (jquery)

开发者 https://www.devze.com 2023-01-14 00:16 出处:网络
Okay, if I have a html document that looks a bit like this: <div class=\'item\'> ... </div>

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...

0

精彩评论

暂无评论...
验证码 换一张
取 消