我正在尝试创建一个关注/取消关注按钮,该按钮可以重复使用两种方式,而无需刷新页面。从某种意义上说,如果我单击“关注”,它会通过我的 PHP 文件将关注数据添加到数据库中,然后在其位置显示“取消关注”按钮,反之亦然,这一切都很好。但是,一旦它显示相反的按钮,在刷新页面之前我无法单击它?我怎样才能使每个功能以我想要的方式同时为每个按钮工作?
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>