2011-06-10 63 views
4

我正在做一个jQuery.post到一个PHP文件,并且该文件返回的是我的值。

问题是:为什么$(this) dosent在回调函数中工作? 任何警报传递的东西来展示,使用$(this),回报就是我null

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

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

    ) 

}); 

回答

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; 
     }     
    ) 
}); 
+0

谢谢,工作的perfetc。 – 2011-06-10 13:33:37

+5

最好使用['.ajax()'](http://api.jquery.com/jQuery.ajax/)而不是'.post()',以便设置'context'选项。 – Wiseguy 2011-06-10 13:36:00

+1

@Wiseguy:提示,请看看。 – 2011-06-10 13:37:00

2
$(".class").live("focusout", function(){ 
    var this = $(this); 
    jQuery.post("phpfile.php",{ 
     someValue: someValue 
    },function(data){ 
     // Now use this instead of $(this), like this.hide() or whatever. 
    }) 
}); 

$(这)在您的例子是指的在$。员额我想。

+2

在'this'调用之前添加一个'var'声明,否则它会将'this'变量泄漏到全局范围中。 – Femi 2011-06-10 13:49:00

+0

好通话费米。 – dotty 2011-06-10 13:53:21