2013-07-23 50 views
1

我正在嘗試創建一個可以重複執行兩種方式而無需刷新頁面的Follow/Unfollow按鈕。它的功能非常完美,如果點擊「Follow」,它會通過我的PHP文件將後續數據添加到數據庫中,然後在它的位置顯示「Unfollow」按鈕,反之亦然,這一切都很好。但是,一旦它顯示相反的按鈕,我不能點擊它,直到我刷新頁面?我該如何做到這一點,以便每個按鈕可以按照我的意願同時用於每個按鈕?jQuery/Ajax - 關注/取消關注按鈕,重複功能

的jQuery/AJAX:

<script> 
$(function() { 
$(".followUser").click(function() 
{ 
var userid = $(this).attr("id"); 
var dataString = 'userid='+ userid ; 
var parent = $(this); 

$("#followButton").fadeOut(300); 
$.ajax({ 
type: "POST", 
url: "follow.php", 
data: dataString, 
cache: false, 

success: function(html) 
{ 
$("#followButton").html('<button id="' +userid '" name="unfollow" class="btn btn-danger unfollowUser">Unfollow</button>'); 
$("#followButton").fadeIn(300); 

} 
}); 
return false; 
}); 
}); 

$(function() { 
$(".unfollowUser").click(function() 
{ 
var userid = $(this).attr("id"); 
var dataString = 'userid='+ userid ; 
var parent = $(this); 

$("#followButton").fadeOut(300); 
$.ajax({ 
type: "POST", 
url: "unfollow.php", 
data: dataString, 
cache: false, 

success: function(html) 
{ 
$("#followButton").html('<button id="' +userid '" name="follow" class="btn btn-info followUser">Follow</button>'); 
$("#followButton").fadeIn(300); 

} 
}); 
return false; 
}); 
}); 
</script> 

HTML:

<div id="followButton"> 

    //if isn't following 
    <button id="1" name="follow" class="btn btn-info followUser">Follow</button> 

    //if is following 
    <button id="1" name="unfollow" class="btn btn-danger unfollowUser">Unfollow</button> 

</div> 

回答

2

在你對php腳本生成按鈕設置按鈕,單擊功能文檔加載。

但是在ajax success上,您將用新按鈕替換#followButton的內容。所以之前的.click已經丟失。

您有幾種選擇:

  1. 創造新的按鈕後,加入onClick事件
  2. 您後續/取消關注按鈕
  3. 簡單使用淡入/淡出
+0

有沒有重置功能的方法爲新添加的按鈕工作? – Engine

+1

這就是你要找的東西http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements – Majky

0
Use show hide on clicking on like button show unlike and hide like and vice-versa. then it will work fine 

$("#hide").click(function(){ 
    $("tagname").hide(); 
}); 

$("#show").click(function(){ 
    $("tagname").show(); 
}); 

hope it will help you