2012-08-05 60 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