Difference between $(this) and this in jquery

2019-01-07 15:23发布

What is the fundamental difference between using $(this) vs this

$('.viewComments').click(function(ev){
    //returns the desired value
    alert(this.getAttribute('id'));

    //Gives an error sayin function is not defined 
    alert($(this).getAttribute('id'));

    //returns the desired value
    alert($(this).attr('id'));
});

What I thought was "$(this)" will contain all functions that "this" has and more..But that doesn't seem to be the case.

So what exactly is $(this)? and

Hw do I know what functions are available when I'm using it? (I know I can get them through firebug. but I would like to know if there any some other way- some doc may be)

标签: jquery this
7条回答
Anthone
2楼-- · 2019-01-07 16:02

$(this) is a jQuery object and you can use the power and beauty of jQuery, but with 'this' keyword, one need to use native JavaScript.

查看更多
淡お忘
3楼-- · 2019-01-07 16:05

this is the DOM object, whereas $(this) is the jQuery wrapper around same.

When using this, you can call DOM methods on it, but not jQuery methods. When using $(this), you can call jQuery methods on it, but not DOM methods.

查看更多
Juvenile、少年°
4楼-- · 2019-01-07 16:06

$(this) is the current object that was selected using a jQuery selector or event attached to the object.

so if you have $('#myelement').click(..... then $(this) referes to the element that was clicked on so that $(this).hide() hides that element.

查看更多
迷人小祖宗
5楼-- · 2019-01-07 16:07

$(this) - represent current DOM element on which event this function is called

The this keyword - In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of.

查看更多
叼着烟拽天下
6楼-- · 2019-01-07 16:07

in jQuery the $() notation is a shorthand for the jQuery selector, so if you say $(this) you are asking jQuery to re-select your object. Then you have the usual jQuery functions available. "this" is the object selected by the outer jQuery call.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-07 16:19

Here are two articles that you may find helpful:

What is this? by Mike Alsup

jQuery's this: demystified by Remy Sharp

查看更多
登录 后发表回答