Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

jQuery Object array notation

I'm new to jQuery, and I'm having a little trouble understanding its array notation for objects. Reading the jQuery docs and this article, it seems that you can refer to the nth item in an object returned by a selector by doing something like

$('.foo')[n];

Correct? Should I be able to use jQuery manipulation/effects functions in tandem? Something like (this isn't working for me)

$('.foo')[0].hide();

I've also tried, to no avail:

var arr = $('.foo').get();
arr[0].hide();

Is there something wrong in my syntax? What's the best way to do what I'm trying to do here?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The [0] array notation and the .get() method both return a reference to a DOM element within the jQuery object, and you can't use jQuery methods on DOM elements.

Try the eq() method instead, because it returns a new jQuery object:

$('.foo').eq(0).hide();

Note also that having used the array notation or .get() to get a reference to a DOM element means you can then get direct access to the DOM element's properties, e.g.:

var firstElId = $('.foo')[0].id;

...with a second note that $('.foo')[0] will be undefined and $('.foo')[0].id will give an error if there are no elements matching the '.foo' selector.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...