在回调函数中访问$(this)

时间:2022-02-11 14:50:23

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 value, but uses a callback function.

我正在努力将prompt()更改为jPrompt(),因为IE会阻止prompt()运行。问题是$(this)不再正常工作,因为jPrompt()不返回值,而是使用回调函数。

So lets say I have something like this, which 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 access $(this) properly?

如何正确访问$(this)?

3 个解决方案

#1


Try this:

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

#2


You could use a closure:

你可以使用一个闭包:

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

#3


The problem is that you're trying to access the 'r' as an element. jPrompt is going to pass the text entered as 'r'.

问题是你试图将'r'作为一个元素来访问。 jPrompt将传递输入为'r'的文本。

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

#1


Try this:

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

#2


You could use a closure:

你可以使用一个闭包:

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

#3


The problem is that you're trying to access the 'r' as an element. jPrompt is going to pass the text entered as 'r'.

问题是你试图将'r'作为一个元素来访问。 jPrompt将传递输入为'r'的文本。

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