Accessing $ (this) in a callback function

I am working on changing prompt () to jPrompt () since IE is blocking the prompt () function. The problem is that $ (this) no longer works correctly because jPrompt () does not return a value, but uses a callback function.

So, let's say I have something like this that works:

$("a.foo").click(function(){
    $(this).text(prompt("Type Something",""));
}

      

When I convert it to this it breaks:

$("a.foo").click(function(){
    jPrompt("Type something:","","", function(r) {
        $(this).text(r);
    }
}

      

How do I get $ (this) correctly?

+1


source to share


3 answers


Try the following:



$("a.foo").click(function(){
    var that = this;
    jPrompt("Type something:","","", function(r) {
        $(that).text(r);
    }
}

      

+5


source


You can use closure:



$("a.foo").click(
  function(){
    var self = this;
    return function() {
      jPrompt("Type something:", "", "", function(r) { 
        $(self).text(r); 
      });
    }
  }()
);

      

+1


source


The problem is you are trying to access the "r" element. jPrompt is going to pass the text entered as "r".

$("a.foo").click(function(){
    jPrompt("Type something:","","", function(r){
        alert(r); //This will show the text entered.
    });
});

      

0


source







All Articles