Accessing $(this) within a callback function

后端 未结 3 1452
难免孤独
难免孤独 2021-01-16 04:43

I\'m working on changing prompt() to jPrompt() since IE blocks prompt() from running. The problem is $(this) no longer works correctly because jPrompt() doesn\'t return a v

相关标签:
3条回答
  • 2021-01-16 05:23

    Try this:

    $("a.foo").click(function(){
        var that = this;
        jPrompt("Type something:","","", function(r) {
            $(that).text(r);
        }
    }
    
    0 讨论(0)
  • 2021-01-16 05:32

    The problem is that you're trying to access the 'r' as an 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 讨论(0)
  • 2021-01-16 05:41

    You could use a closure:

    $("a.foo").click(
      function(){
        var self = this;
        return function() {
          jPrompt("Type something:", "", "", function(r) { 
            $(self).text(r); 
          });
        }
      }()
    );
    
    0 讨论(0)
提交回复
热议问题