2012-08-09 82 views
0

可能重複:
how to access the $(this) inside ajax success callback function

我有這樣的代碼:

$('.each_button').click(function(){ 

$.ajax({ type: 'POST', url: process.php, data: data, success: function(data){ 

///// 
     } 
    }) 
}); 

我如何可以訪問非常$('.each_button')觸發事件?我試過$(this)但它不起作用,可能是因爲它在另一個功能裏面。

非常感謝。在AJAX調用之前變量

+0

argh ..沒有看到它的建議..我可以'關閉它,現在有人回答了 – eric01 2012-08-09 22:29:36

+1

只是標記了我自己。謝謝你讓我知道。問候 – eric01 2012-08-09 22:32:04

回答

5

每個人都想使用一個變量由於某種原因。這不是必需的。

$('.each_button').click(function(){ 

    $.ajax({ 
     context: this, // <-- do this instead... 
     type: 'POST', 
     url: process.php, 
     data: data, 
     success: function(data) { 
       // ...now 'this' is the element you want 
      alert(this.className); 
     } 
    }); 

}); 

或者使用$.proxy如果你喜歡...

$('.each_button').click(function(){ 

    $.ajax({ 
     type: 'POST', 
     url: process.php, 
     data: data, 
     success: $.proxy(function(data) { 
       // ...now 'this' is the element you want 
      alert(this.className); 
     }, this) // <-- bind the context 
    }); 

}); 

一個好處這些方法是,它可以讓你重用success功能...

function ajax_success(data) { 
    alert(this.className); 
} 

$('.each_button').click(function(){ 
    $.ajax({ 
     context: this, 
     type: 'POST', 
     url: process.php, 
     data: data, 
     success: ajax_success 
    }); 
}); 
+2

第一個例子很整潔!我沒有意識到功能!非常感謝。 – OptimusCrime 2012-08-10 00:08:05

1

搭上:

$('.each_button').click(function(){ 

    var $this = $(this); 

    $.ajax({ type: 'POST', url: process.php, data: data, success: function(data){ 

      alert($this); 

     } 
    }) 
}); 
2

你可以保存對象到另一個變量和訪問它的function(data)內。

事情是這樣的:

$('.each_button').click(function(){ 
    var $obj = $(this); 
    $.ajax({ 
     type: 'POST', 
     url: process.php, 
     data: data, 
     success: function(data) { 
      $obj.val(data.foobar); 
     } 
    }) 
}); 
+1

哦,不使用'var'?不是一個好主意。 – kapa 2012-08-10 00:12:39

+1

@bažmegakapa:vups,忘記了。謝謝你提醒我。 – OptimusCrime 2012-08-10 00:57:01

相關問題