开发者

Execute a function on the first element matching selection using jQuery

I know $('.test').each(testFunction); invokes the testFunction for all matching .test elements on the page. How do I tell it to do just the first matching one.

I 开发者_如何学编程tried $('.test:first').each(testFunction); and it still seems to run for all of them.


:first should work as you expected http://jsfiddle.net/guard/r5nUZ/


I think you should be able to use the .first() function in place of .each(). Looking at the documentation http://api.jquery.com/category/traversing/, that appears to be the function of choice.


(function($) {
    $.fn.testFuntion = function() {
    return each( function() {
       console.log(this);
    });
    }
})( jQuery );
//$('.test:first').testFuntion();

or

$('.test').each(function(i) { 
  if ( i == 0 ) {
      testFuntion();
  }
});


try

$(".test").first();

this should select just the first element from that list. also if you are only trying to run it on one element why are you using each?

just do

testFuntion($(".test").first());
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜