jQuery每一个
var slides = $(".promo-slide"); slides.each(function(key, value){ if (key == 1) { this.addClass("first"); } });
为什么我会收到错误说:
Uncaught TypeError: Object # has no method 'addClass'
从上面的代码?
在jQuery回调函数中, this
指的是DOM对象,而不是jQuery对象。
var slides = $(".promo-slide"); slides.each(function(key, value){ if (key == 0) { // NOTE: the key will start to count from 0, not 1! $(this).addClass("first"); //------^^----^ } });
但是:在您的情况下,这更容易:
$(".promo-slide:first").addClass("first");
顺便说一句,我发现在包含带有$
的jQuery对象的变量前缀是一个有用的约定:
var $slides = $(".promo-slide"); $slides.each( /* ... */ );
你可能想做:
$(this).addClass