2012-08-05 53 views
1

我有以下脚本,设计使用AJAX数据更改收藏夹按钮的外观,以及提交/删除到MySQL表:的jQuery/AJAX脚本添加/删除类按钮不灵的

$(document).ready(function() { 
jQuery("input.before").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'); 
     }, 
     error: function() { 
     jQuery('#error').html('<div>Error! Unable to add favourite.</div>'); 
     } 
    }); 
}); 

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

,通过点击几个按钮,一个触发,即:

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

脚本的第一部分“之前”删除类和预期“后”添加类,但是当我再试试点击'after'后面的按钮,脚本的第二部分不起作用,即c按钮的副本不会变回“之前”。有人能告诉我为什么这不起作用吗?

回答

2

你第一次点击处理程序在那个时候即是由jQuery("input.before")返回,同为第二处理的项目,以处理按钮事件与.on()特定随时类使用事件委托绑定到该按钮与before

$(document).ready(function() { 
jQuery(document).on("click", "input.before", 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'); 
     }, 
     error: function() { 
     jQuery('#error').html('<div>Error! Unable to add favourite.</div>'); 
     } 
    }); 
}); 

jQuery(document).on("click", "input.after", function(){ 
    var $this = $(this); 
    jQuery.ajax({  
     url: 'removefav.php', 
     type: 'POST', 
     data: {'id': $this.closest("div").attr("id"),is_ajax: 1}, 
     success: function(html) { 
     $this.removeClass('after'); 
     $this.addClass('before'); 
     }, 
     error: function() { 
     jQuery('#error').html('<div>Error! Unable to remove favourite.</div>'); 
     } 
    }); 
}); 
}); 
+0

谢谢,现在脚本运行良好。 – Nick 2012-08-05 23:59:39