What is jQuery $ (this) related to this piece of code?

$(document).ready(function() { $(".po").click(function(){ var po = $(this).text(); var dataString = 'po='+ po; $.ajax ({ type: "GET", url: "projectitems.php", data: dataString, cache: false, success: function(html) { $(this).closest(".resultsItems").html(html); } }); }); }); 

Line $(this).closest(".resultsItems").html(html); What exactly does (this) refer to? I am trying to add ajax return to <td> called by .resultsItems, but only to what is under the selector clicked on the link. Is it possible?

Just to make it clear, I am not asking what (this) means in jQuery, I am asking what (this) means in my code above!

+6
jquery
source share
3 answers

this refers to the settings object $.ajax() . To get what you want, you need to support this with the context parameter as follows:

 $.ajax({ context: this, type: "GET", url: "projectitems.php", data: dataString, cache: false, success: function(html) { $(this).closest(".resultsItems").html(html); } }); 
+9
source share

On jQuery website:

The this object for all of them will be the object in the context property passed to $.ajax in the settings; if not specified, this will be a link to the Ajax settings themselves.

+3
source share

More about this keyword here

Basically, in your case, this refers to the window object, because it is the window object that raised the success event when ajax was called. However, you can grab the $(".po") just above the ajax call by doing:

 var that = this; 

Then, if you use that.closest()... , which will reference the $(".po") object

0
source share

All Articles