Jquery替换类只能以一种方式工作

时间:2015-01-27 15:47:52

标签: jquery class addclass removeclass

对于一个学校项目,我正在制作一个社交媒体页面,我已经到了这一点,我必须制作一个关注/取消关注按钮。我做了2节课。按下一个看起来像普通按钮的类(class1)和看起来像那个按钮的一个(class2)。

通常选择class1但是当你点击我要显示class2的按钮时它应该显示“unFollow”文本。

我希望它能同时发挥作用。所以,当我点击现在让class2变成class1的按钮时,那就是我无法解决的问题。

以下是我的代码:

    $(document).ready(function()
{
    $(".FollowB").click(function(){
        $(this).removeClass("FollowButton")
        $(this).addClass("unFollowButton")
        $(this).text("Unfollow")
    }); 
});

if $(this).hasClass("unFollowButton"){
    $(this).removeClass("unFollowButton")
        $(this).addClass("FollowButton")
        $(this).text("Follow")
}

有人可以告诉我我的代码有什么问题,更重要的是为什么它不起作用?

2 个答案:

答案 0 :(得分:1)

主要问题似乎是第二个if位于$(document).ready()处理程序之外,其$(this)是全局Window对象,而不是按钮本身。

最简单的验证方法是console.log($(this))之前的if

实现您的功能的最简单方法是:

// I'm assuming the relevant buttons are of class="FollowB"
// *and* they start with a class of either 'follow' or 'unfollow':
$(".FollowB").on('click', function () {
    // $(this) is the clicked .FollowB button-element:
    $(this)
        // toggleClass replaces 'follow' with 'unfollow'
        // and vice-versa; removing the present-class and
        // adding the non-present class:
        .toggleClass('follow unfollow')
        // using the anonymous function of text() to
        // update the text:
        .text(function(){
            // if the clicked element has the class 'follow'
            // we set the text to 'unfollow, if it does not
            // then we set the text to 'follow':
            return $(this).hasClass('follow') ? 'unfollow' : 'follow';
        });
    });



$(".FollowB").on('click', function() {
  $(this)
    .toggleClass('follow unfollow').text(function() {
      return $(this).hasClass('follow') ? 'unfollow' : 'follow';
    });
});

button {
  text-transform: capitalize;
}
.unfollow {
  border: 2px solid #f00;
}
.follow {
  border: 2px solid #0f0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="FollowB unfollow">Follow</button>
&#13;
&#13;
&#13;

参考文献:

答案 1 :(得分:0)

 $(".foo").click(function() {
   if ($(this).hasClass('follow')) {
     $(this).removeClass("follow")
     $(this).addClass("unfollow")
     $(this).text("Unfollow")
   } else {
     $(this).removeClass("unfollow")
     $(this).addClass("follow")
     $(this).text("follow")
   }
 });
.follow {
  color: red;
}
.unfollow {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='foo follow'>Follow</div>