Home > Web Front-end > JS Tutorial > body text

Examples to explain the difference between this and $(this) in JQuery_jquery

WBOY
Release: 2016-05-16 16:28:31
Original
1398 people have browsed it

This is rarely used in jquery. When I looked at the code, I found that it was used, so I debugged the value of this and thought that was the case. Still quite useful. Here is a summary of the differences and uses of this and $(this).

 What does $(this) generate?

What does $() generate? In fact, $()=jquery() means that it returns a jquery object.

Usually we use $() directly for simplicity. In fact, this function omits a parameter context. Select the matching object based on the selector, that is, $(selector, context), and return it in the form of a jQuery wrapper set.

Context can be a Dom object collection or a jQuery packaging set. Passing it in means selecting matching objects from the context. If it is not passed in, it means the scope is the document object (that is, all objects on the page), that is, $(selector)=$ (selector,document).

This refers to the html object that calls the function.

Example:

Copy code The code is as follows:

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

This here is actually an Html element (textbox), and this is in js. The textbox has a text attribute, so there is no problem in writing it this way.

Copy code The code is as follows:

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

$(this) here is a JQuery object, and jQuery objects do not have a title attribute, so writing this is wrong.

Conclusion:

 This indicates that the current context object is an html object, and you can call the properties and methods owned by the html object.

$(this), the context object represented is a jquery context object, which can call jquery methods and attribute values.

Instance (tab):

Copy code The code is as follows:
tabs($("#nav a"), $(".content"));
function tabs(tab, content){
content.hide();
content.eq(0).show();
tab.click(function(){
var index = tab.index(this);
tab.removeClass("current");
$(this).addClass("current");
content.hide();
content.eq(index).animate({opacity:'show'}, 200);
});
}

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template