Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - parent() not working within callback function

I was testing with parent() and closest(), none work within function.

TD stays the same, no change using this method:

$.get('form.php', function(data){ 
    alert(data); 
    $(this).closest('td').html('Done!'); 
});

TD gets updated, this method works:

$.get('form.php', function(data){ 
    alert(data); 
}); 
$(this).closest('td').html('Done!');

Can you please help me figure out why does closest('td') not working within callback function?

like image 745
Edi Budimilic Avatar asked Sep 13 '10 16:09

Edi Budimilic


2 Answers

Your this inside of the callback function has another scope than the this on the outside. You need to do something like this:

var self = this;
$.get('form.php', function(data) {
    alert(data);
    $(self).closest('td').html('Done!');
});

You can use jQuery's .proxy()-function to achieve the desired effect, too, like patrick dw pointed out in his post. I recommend reading through this document.

like image 60
jwueller Avatar answered Oct 16 '22 18:10

jwueller


You can use jQuery's $.proxy method for the second argument for $.get() to retain the desired value of this.

$.get('form.php', $.proxy(function(data) {
    alert(data);
    $(this).closest('td').html('Done!');
}, this));
like image 3
user113716 Avatar answered Oct 16 '22 19:10

user113716