写相关和多功能

时间:2016-08-18 13:39:54

标签: jquery

我为以下代码编写代码:

(1)

// Follow Button click action
$('body').on('click' , '.btn-follow', function() { 
  $(this).removeClass('btn-follow').addClass('btn-following');
  $(this).text('Following');

  // call followingHover function to get the action of that button
  followingHover();
});

(2)

// Hover on Following Button
function followingHover() {
  $('.btn-following').hover(
    function() {
      $(this).addClass('btn-unfollow');
      $(this).text('Unfollow');
    }, function() {
      $(this).removeClass('btn-unfollow');
      $(this).text('Following');
    }
  );
};

followingHover();

(3)

// Following Button click action
$('body').on('click', '.btn-following', function() { 
  $(this).removeClass('btn-following').addClass('btn-follow');
  $(this).text('Follow');
});

但问题是,我无法将这些功能整合在一起。因此,在一个函数内部,其他函数以错误的方式调用。如何才能使这些功能写得很好?你能帮帮我吗?

Fiddle Demo For testing

1 个答案:

答案 0 :(得分:3)

您可以查看此示例。 Fiddle

(1)                跟随         

    <div class="action-list-item">
      <a href="#" class="btn  btn-action btn-follow" type="button">Follow</a>
    </div>

    <div class="action-list-item">
      <a href="#" class="btn  btn-action btn-following" type="button">Following</a>
    </div>

(2)

  $(document).ready(function(){

$("body").on("mouseenter",".btn-following",function(){
$(this).text("Unfollow")
}).on("mouseleave",".btn-following",function(){
 $(this).text("Following")
})
})
// Following Button click action
$("body").on("click",".btn",function(){
if($(this).hasClass("btn-follow")){
   $(this).text("Following");
   $(this).removeClass("btn-follow").addClass("btn-following");

}else{
 $(this).text("Follow");
 $(this).removeClass("btn-following").addClass("btn-follow");
}
 })

(3)

.action-list-item {
  margin: 20px;
}

.btn-action {
  background-color: yellow;
  color: #333;
  border-color: #af932c;
  width: 86px;
}
.btn-following {
  background-color: green;

}
.btn-following:hover{
  background:red;color:white;
  content:"Unfollow";
  }
.btn-action.btn-unfollow {
  background-color: #9e3515;
}