2011-09-08 125 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)以避免每次使用它的時間來關注一下吧...