2011-09-08 126 views

回答

4

如何通过.each获取当前循环元素if if statement?

用途:

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

例子:

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

请注意,您还可以通过使用this关键字获得DOM对象而不是jQuery对象。

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

缓存$(this)以避免每次使用它的时间来关注一下吧...