开发者

JQuery each loop - do something with currently looped element

开发者 https://www.devze.com 2023-04-03 06:29 出处:网络
I have following .ea开发者_如何学Goch jQuery loop. $(\'.category\').each(function(index) { if( $(\'.category > span\').parent().next(\'h2\') ) {

I have following .ea开发者_如何学Goch jQuery loop.

$('.category').each(function(index) {
    if( $('.category > span').parent().next('h2') ) { 

        // get currently looped element which follows the condition
    }

});

How to get currently looped element through .each inside the if statement?


How to get currently looped element through .each inside the if statement?

Use:

$(this) // represents current iterated element in wrapped set

Example:

$('.category').each(function(index) {
    if( $('.category > span').parent().next('h2') ) { 
      $(this).css('color', 'red');
    }
});

Note that you could also get DOM object instead of jQuery object by using this keyword.


$('.category').each(function(index) {
 var that = $(this);
 if( $('.category > span').parent().next('h2') ) { 
  // do something with `that`
 }
});

Cached $(this) to avoid having to look it up every time you use it…

0

精彩评论

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