开发者

How do I perform a function on a single jQuery object?

I often make use of the each method in jQuery, such as the following:

 $('#thing img').each(function(){
     //do some stuff
 });

...where the function is performed on each element in the jQuery object. Is there a method/syntax for performing an action on the only (or first matched) element in the object?

I'm imagining something like

 $('#thing img').do(function(){
     //do some stuff
 });

I don't need 开发者_JS百科to use jQuery but can, as the application in question already makes use of it.


Just don't complicate the matter:

var thisImg = $('#thing img')[0];
//do some stuff with thisImg


Just limit the selector to the first element like so:

$('#thing img:eq(0)').each(function(){
 //do some stuff on the first response only
});


You can use eq selector.

Try:

$('#thing img').eq(0).each(function(){
     //do some stuff
 });

or

$('#thing img:eq(0)').each(function(){
     //do some stuff
 });

or(based on @John's inputs)

   $('#thing img').first().each(function(){
         //do some stuff
     });


you use return false statement to break the loop once your stuff is done

 $('#thing img').each(function(){
     //do some stuff for 1st matched item then

return false;
 });


Check out This but not $(this)

(function($){
    $.fn.me = function(func) {
        func.call(this[0]);
        return this;    
    }
})(jQuery);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜