php - jQuery/Ajax - 关注/取消关注按钮,重复功能

标签 php javascript jquery ajax function

我正在尝试创建一个关注/取消关注按钮,该按钮可以重复使用两种方式而无需刷新页面。从某种意义上说,它的功能非常完美,如果我单击“关注”,它会通过我的 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>

最佳答案

在文档加载时,您可以在 php 脚本生成的按钮上设置按钮点击功能。

但是在 ajax success 上,您正在用新按钮替换 #followButton 的内容。所以之前的 .click 丢失了。

你有几个选择:

  1. 创建新按钮后添加onClick事件
  2. 在关注/取消关注按钮上简单使用淡入/淡出

关于php - jQuery/Ajax - 关注/取消关注按钮,重复功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17807678/

相关文章:

asp.net-mvc - jQuery UI 自动完成插件 - 问题

jquery - 如何显示正在运行的谷歌应用程序引擎任务队列任务的进度?

php - 将字符串从 PHP 传递到 JavaScript 函数

php - Symfony 2 功能测试 : bypassing ssl

php - 我怎样才能在 laravel 5.4 中获得正确的文件扩展名

javascript - Visual Studio JavaScript 调试速度极慢

PHP、Mysql向行中插入图片

javascript - 在另一个框架中显示 div

javascript - 检查一个点是否在 OpenLayers 3 中的多边形内

javascript - jQuery滑动删除div栏