jquery - 编写相关的和多个函数

标签 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

最佳答案

你可以检查这个例子。 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;
}

关于jquery - 编写相关的和多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39019753/

相关文章:

javascript - Jquery帮助选择输入字段

jquery - History.js + 表单?

javascript - 使用 jquery/ajax 检查 url 是否存在

php - JSON 结果不显示完整日历中选定的事件

jquery - 使用 jQuery 预加载图像

javascript - 查找最接近的元素并在元素之前插入

javascript - 无法获取jquery函数外部变量的值

jQuery 选择器无法通过 ID 找到我的元素

javascript - 将 HTML NodeList 读入数组

jQuery - 悬停很多次会破坏 javascript?