在ajax回调jquery中使用$(this)

Ric*_*nns 4 javascript jquery

我正在做一个jQuery.postPHP文件,文件返回给我一个值.

问题是:为什么$(this)dosent在回调函数中工作?任何提示通过显示,使用$(this),返回我的警报null

$(".class").live("focusout", function(){

    jQuery.post("phpfile.php",
       {
           someValue: someValue
       },
       function(data)
       {
             // why the $(this) dosent work in the callback ?
       }                

    )

});
Run Code Online (Sandbox Code Playgroud)

Bru*_*oLM 13

在那种情况下this,不再是同一个对象.之前保存参考并稍后使用:

$(".class").live("focusout", function(){
    var $this = $(this);
    jQuery.post("phpfile.php",
       {
           someValue: someValue
       },
       function(data)
       {
           // 'this' inside this scope refers to xhr object (wrapped in jQuery object)
           var x = $this;
       }                
    )
});
Run Code Online (Sandbox Code Playgroud)

  • 最好使用[`.ajax()`](http://api.jquery.com/jQuery.ajax/)而不是`.post()`,这样你就可以设置`context`选项. (5认同)