2011-06-10 36 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