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

Chr*_*tow 1 jquery

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

所以,让我说我有这样的东西,它有效:

$("a.foo").click(function(){
    $(this).text(prompt("Type Something",""));
}
Run Code Online (Sandbox Code Playgroud)

当我将其转换为此时,它会中断:

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

如何正确访问$(this)?

Gum*_*mbo 5

试试这个:

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