Javascript jQuery 每个这个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6409039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery each this
提问by o01
var slides = $(".promo-slide");
slides.each(function(key, value){
if (key == 1) {
this.addClass("first");
}
});
Why do I get an error saying:
为什么我收到一条错误消息:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'addClass'
From the above code?
从上面的代码?
回答by Tomalak
Inside jQuery callback functions, this
(and also value
, in your example) refers to a DOM object, not a jQuery object.
在 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");
//------^^----^
}
});
BUT: In your case, this is easier:
但是:在你的情况下,这更容易:
$(".promo-slide:first").addClass("first");
As an aside, I find it a useful convention to prefix variables that contain a jQuery object with a $
:
顺便说一句,我发现将包含 jQuery 对象的变量添加为前缀是一个有用的约定$
:
var $slides = $(".promo-slide");
$slides.each( /* ... */ );
回答by ninjagecko
You probably want to do:
你可能想做:
$(this).addClass