$(this) 与 JavaScript 中的 this
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20718112/
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
$(this) vs this in JavaScript
提问by bizzehdee
When writing JavaScript in jQuery is it best to do:
在 jQuery 中编写 JavaScript 时最好这样做:
$('.select').click(function(e){
$(this).something();
//Or
this.something();
});
Is there any difference? What are the advantages or disadvantages of either way?
有什么区别吗?两种方式的优点或缺点是什么?
回答by meagar
They're completely different. Neither is "better" and you cannot compare their advantages and disadvantages. One is a jQuery object, one is a raw HTML element.
他们完全不同。两者都不是“更好”,您无法比较它们的优缺点。一个是 jQuery 对象,一个是原始 HTML 元素。
回答by Ringo
$(this)
is a jQuery object and this
is a pure DOM Element object. See this example:
$(this)
是一个 jQuery 对象,this
是一个纯 DOM 元素对象。看这个例子:
$(".test").click(function(){
alert($(this).text());
//and
alert(this.text()); // error no method
});
回答by Timovdz
The other answers are correct, however I would like to add that this
within the context of $.fn.function
also refers to the jQuery object.
其他答案是正确的,但是我想this
在$.fn.function
也指 jQuery 对象的上下文中添加它。
For example:
例如:
$.fn.function = function() {
this.width();
}
回答by MichaC
In the callback scope of jquery of an event handler this
is the pure element.
在事件处理程序的 jquery 回调范围内this
是纯元素。
$(this)
would wrap it again into a jquery instance
$(this)
将它再次包装成一个 jquery 实例
So the result is very different and it simply depends on what you need...
所以结果是非常不同的,它只取决于你需要什么......
回答by Asmita
this
and $(this)
will give different results as $(this)
is jQuery instance and this
is HTML element.
this
并且$(this)
会给出不同的结果,就像$(this)
jQuery 实例和this
HTML 元素一样。