2011-06-10 7 views
4

나는 PHP 파일에 jQuery.post을하고 있는데, 파일 반환 값이 나입니다.

질문 : 왜 $(this) dosent 콜백 함수에서 작동합니까? $(this)를 사용하여 보여 줄게 통과 어떤 경고, 수익률이 경우 this 나에게 null

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

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

    ) 

}); 

답변

13

있어 더 이상 같은 개체가 아닙니다. 전에 참조를 저장하고 나중에 사용 : 귀하의 예제에서

$(".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. –

+5

'.post()'대신 ['.ajax()'] (http://api.jquery.com/jQuery.ajax/)를 사용하면'context' 옵션을 설정할 수 있습니다. – Wiseguy

+1

@Wiseguy : 끝 부분에 대해 살펴 보겠습니다. –

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. 
    }) 
}); 

$ (이) 내가 생각 $ .post로 다스 려했다.

+2

'this' 호출 전에'var' 선언을 추가하면 전역 변수에'this' 변수가 누설됩니다. – Femi

+0

좋은 대화 Femi. – dotty