2011-04-17 95 views
1

我想一些Ajax後的CSS類添加到我的按鈕:添加類按鈕jQuery中

$('a.vote-up-0').click(function() { 

    var id = $(this).siblings('.reply-id').val(); 
    var ajax_auth_token = $('#auth_token').val(); 


    $.post('user/?action=ajax', { 
     vote_type: 'up', 
     reply_id: id, 
     auth_token: ajax_auth_token 
    }, function(data, return_status) { 

     var json_data = jQuery.parseJSON(data); 

     switch(json_data.r_message) 
     { 
      case "success": 
       output = "Yay it works!"; // change 
       alert(output); 
       $(this).addClass('vote-up-1'); // ** the culprit ** 
      break; 

警報的作品,但它不類票上加1它。在頁面上有幾個相同類的實例(即投票0),所以如果我改變(這個)爲'投票0',它會改變所有這些。有人有主意嗎?

+0

放警報 – Nighil 2011-04-17 17:34:32

回答

0

兄弟:$(this).addClass('vote-up-1'); // ** the culprit **是真正的罪魁禍首。 $(this)在此範圍內不可用,所以最好在執行任何ajax之前獲取按鈕的句柄。如:

var btnHnd = $(this);現在你可以做的東西后:$.post('user/?action=ajax', { ...

2

最多在你的 「點擊」 處理器的頂部,藏匿this值:

var theButton = this; 

然後,在你的 「員額()」 處理程序:

$(theButton).addClass('vote-up-1'); 

的問題是,當jQuery調用你的「.post()」處理函數時,this不會引用按鈕。因此,您將副本保存到本地變量中,並且在時間到了的時候它會在那裏等待處理程序。

0

變化的罪魁禍首線和檢查後,該

$(putyourbuttonidhere).addClass('vote-up-1');