Javascript 这个 vs $(this)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7479282/
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)
提问by user864600
Possible Duplicate:
jQuery $(this) vs this
I'm new to this and trying to get my concept right. There has been many instances of the use of "this
" and "$(this)
". Can someone please explain the difference and in what condition that we use the two different "this"?
我是新手,并试图让我的概念正确。使用“ this
”和“ $(this)
”的例子很多。有人可以解释一下区别以及我们在什么情况下使用两个不同的“this”?
回答by Flambino
In jQuery functions, this
most often refers to the actual DOM element you're dealing with, whereas $(this)
returns a jQuery object that wraps the element.
在 jQuery 函数中,this
最常指的是您正在处理的实际 DOM 元素,而$(this)
返回一个包装元素的 jQuery 对象。
In JavaScript, this
always refers to the current scope. Many of jQuery's functions will set that scope to be the element you're working with.
在 JavaScript 中,this
总是指当前作用域。jQuery 的许多函数都会将该范围设置为您正在使用的元素。
For instance
例如
$("#someElement").click(function() {
this; // the element itself
$(this); // a jQuery wrapper-object around the element
});
The point is, that the jQuery object has all the jQuery functions (like .detatch()
or .prependTo()
etc.), while the DOM element is what the browser provides. In the example above, the element would be exactly the same as what you'd get, if you called document.getElementById("someElement")
关键是,jQuery 对象具有所有 jQuery 功能(例如.detatch()
或.prependTo()
等),而 DOM 元素是浏览器提供的。在上面的示例中,元素将与您得到的完全相同,如果您调用document.getElementById("someElement")
回答by austinbv
$(this)
refers to a jquery object, this
refers to this
in the current scope
$(this)
指的是一个jquery对象,this
指的是this
在当前范围内
回答by Vivin Paliath
$(this)
is a jQuery object. this
refers to the value of this
within the current scope. You typically use $(this)
inside a callback when you want to convert the element that triggered the event, into a jQuery object. You can do this to pretty much any DOM element, so $(document.getElementById("#myElement"))
is also valid, and is a jQuery object that represents the DOM element with id "myElement".
$(this)
是一个 jQuery 对象。this
指this
当前范围内的值。$(this)
当您想要将触发事件的元素转换为 jQuery 对象时,您通常在回调中使用。您几乎可以对任何 DOM 元素执行此操作,因此$(document.getElementById("#myElement"))
它也是有效的,并且是一个 jQuery 对象,它表示 ID 为“myElement”的 DOM 元素。