6

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?

Teja Kantamneni
  • 17,402
  • 12
  • 56
  • 86
Edi Budimilic
  • 4,526
  • 3
  • 19
  • 22

2 Answers2

6

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.

jwueller
  • 30,582
  • 4
  • 66
  • 70
  • That was quick, and it worked! I wasn't aware that `this` works differently inside of a $.get, another lesson to learn. Thank you both! – Edi Budimilic Sep 13 '10 at 16:35
  • `this` works differently inside different functions. JavaScript has function scope. `this` points to the current context/scope. – jwueller Sep 13 '10 at 16:40
3

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));
user113716
  • 318,772
  • 63
  • 451
  • 440