JQuery每个循环 - 用当前循环元素做些什么
问题描述:
我有以下.each
jQuery循环。JQuery每个循环 - 用当前循环元素做些什么
$('.category').each(function(index) {
if($('.category > span').parent().next('h2')) {
// get currently looped element which follows the condition
}
});
如何获得目前通过.each
的if
语句中环元素?
答
如何通过.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对象。
答
$('.category').each(function(index) {
var that = $(this);
if($('.category > span').parent().next('h2')) {
// do something with `that`
}
});
缓存$(this)
以避免每次使用它的时间来关注一下吧...