var slides = $(".promo-slide");
slides.each(function(key, value){
if (key == 1) {
this.addClass("first");
}
});
为什么会出现错误提示:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'addClass'
从上面的代码中获得什么信息?
var slides = $(".promo-slide");
slides.each(function(key, value){
if (key == 1) {
this.addClass("first");
}
});
为什么会出现错误提示:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'addClass'
从上面的代码中获得什么信息?
在 jQuery 回调函数内,this
(以及在您的示例中的 value
)指的是 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"); // Or $(value).addClass("first");
//------^^----^
}
});
但是在你的情况下,这更容易:
$(".promo-slide:first").addClass("first");
如果所有的.promo-slide
元素都在同一个容器中,使用纯CSS解决问题就更加简单:
.promo-slide:first-child {
/* ... */
}
作为旁注,我发现在变量名前使用$
作为前缀对于包含jQuery对象的变量非常有用。var $slides = $(".promo-slide");
$slides.each( /* ... */ );
.each
从0开始给出索引,所以在你的第二个代码片段中应该使用$('.promo-slide:eq(1)')
。 - sharat87您可能希望执行以下操作:
$(this).addClass
$()
将this
包装起来,像这样:$(this)
,确保它被视为 jQuery 对象。 - Thor Jacobsen