this vs $(this) [duplicate]

时间秒杀一切 提交于 2019-12-18 10:29:11

问题


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"?


回答1:


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.

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.

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")




回答2:


$(this) refers to a jquery object, this refers to this in the current scope




回答3:


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



来源:https://stackoverflow.com/questions/7479282/this-vs-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!