What is "this"?
In many object-oriented programming languages, this (or self) is a keyword which can be used in instance methods to refer to the object on which the currently executing method has been invoked.
$("#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 at all writing it this way.
But if this is replaced with $(this), that is not the case, and Error– will be reported.
Error Code:
$("#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 it is wrong to write it like this.
JQuery has the attr() method to get/set attributes of DOM objects, so the correct way to write it should be like this:
Correct code:
$("#textbox").hover(
function() {
$(this ).attr('title', 'Test');
},
function() {
$(this).attr('title', 'OK');
}
);
The advantage of using JQuery is that it packages the operations of DOM objects in various browser versions, so it should be a good choice to use $(this) uniformly instead of this.