簡體   English   中英

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

[英]use $(this) in ajax callback jquery

我正在做一個jQuery.post到一個 php 文件,文件返回給我一個值。

問題是:為什么$(this) dosent 在回調 function 中起作用? 使用$(this)傳遞要顯示的任何警報,返回我null

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

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

    )

});

在這種情況下, this不再是同一個 object。 之前保存參考並稍后使用:

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

您的示例中的 $(this) 是指我認為的 $.post 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM