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