2012-08-05 34 views
1

我有以下的jQuery/AJAX腳本:添加和按鈕AJAX腳本中刪除類

jQuery("input.button").click(function(){ 
    jQuery.ajax({  
     url: 'addfav.php', 
     type: 'POST', 
     data: {'id':jQuery(this).closest("div").attr("id"),is_ajax: 1}, 
     success: function(html) { 
     jQuery(this).removeClass('before'); 
     jQuery(this).addClass('after'); 
     jQuery(this).attr('disabled', 'disabled'); 
     }, 
     error: function() { 
     jQuery('#error').html('<div>Error! Unable to add food item.</div>'); 
     } 
    }); 
}); 

它處理上的按鈕單擊像這樣的:

<div id="32"><input type="button" class="button before"/></div> 
<div id="33"><input type="button" class="button before"/></div> 

的添加和刪除類然而,無論如何,但點擊不起作用。它適用於一個帶有ID的單個按鈕,例如:

jQuery("input#button1").click(function(){ 

但是當我使用類時不行。當我使用按鈕的類時,需要做些什麼修改才能讓此腳本添加或刪除類到哪個按鈕被點擊?

回答

1

你應該cashe選擇,請嘗試以下操作:

jQuery("input.button").click(function(){ 
    var $this = $(this); 
    jQuery.ajax({  
     url: 'addfav.php', 
     type: 'POST', 
     data: {'id': $this.closest("div").attr("id"),is_ajax: 1}, 
     success: function(html) { 
     $this.removeClass('before'); 
     $this.addClass('after'); 
     $this.attr('disabled', 'disabled'); 
     }, 
     error: function() { 
     jQuery('#error').html('<div>Error! Unable to add food item.</div>'); 
     } 
    }); 
}); 
+1

謝謝,@Nick歡迎您工作正常 – Nick 2012-08-05 22:59:19

+0

。 – undefined 2012-08-05 23:00:59