JQuery each loop - do something with currently looped element
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…
精彩评论