Home >Web Front-end >JS Tutorial >What is the difference between this and $(this) in jQuery?

What is the difference between this and $(this) in jQuery?

青灯夜游
青灯夜游Original
2020-11-26 16:15:233457browse

Difference: this means that the current context object is an html DOM object, which can call the properties and methods owned by the html object; and the context object represented by "$(this)" is a jquery context object, which can Call jquery's methods and attribute values.

What is the difference between this and $(this) in jQuery?

Related recommendations: "jQuery Video Tutorial"

The difference between the usage of this and $(this) in jquery. Let’s look at the following code first:

$("#textbox").hover(
    function() {
        this.title = "Test";  },
    fucntion() {
        this.title = "OK”;  }
);

This here is actually an Html element (textbox), and textbox has a text attribute, so there is no problem with writing it this way. But if you replace this with $(this), that's not the case, and an error will be reported. The following writing is wrong:

$("#textbox").hover(
    function() {
        $(this).title = "Test";  },
    function() {
        $(this).title = "OK";  }
);

$(this) here is a JQuery object, and the jQuery object does not have a title attribute, so this writing is wrong. JQuery has the attr() method that can get/set attributes of DOM objects, so the correct way to write it should be like this:

$("#textbox").hover(
    function() {
        $(this).attr('title', 'Test');
    },
    function() {
        $(this).attr('title', 'OK');
    }
);

The advantage of using JQuery is that it packages the operations of various browser versions on DOM objects, so It would be a better choice to use $(this) uniformly instead of this.

$()What is generated? In fact, $()=jquery(), then it means that a jquery object is returned.

$(this) is a jquery object that can call jquery methods, such as click(), keyup().

$(function () {
    $('button').click(function () {
       alert(this);//this 表示原生的DOM
       //$(this)表示当前对象,这里指的是button
   }) 
});

Conclusion:
this, indicating that the current context object is a html DOM object, which can call the html object The properties and methods it possesses.
$(this), the context object represented is a context object of jquery, which can call the methods and attribute values ​​of jquery.

For more programming-related knowledge, please visit: Programming Learning! !

The above is the detailed content of What is the difference between this and $(this) in jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn