$(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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:06:34  来源:igfitidea点击:

$(this) vs this in JavaScript

javascriptjquery

提问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 thisis 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 thiswithin the context of $.fn.functionalso 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 thisis 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

thisand $(this)will give different results as $(this)is jQuery instance and thisis HTML element.

this并且$(this)会给出不同的结果,就像$(this)jQuery 实例和thisHTML 元素一样。