jQuery 根据点击次数设置动画

jQuery animating depending on the number of clicks

我一直在尝试编写一个在点击时显示或隐藏某些内容的函数,但我目前停留在 showing/hiding,具体取决于点击按钮的次数。我的代码:

 $(document).ready(function(){
              $("#twitch-pasek-przycisk").click(function(){
                           var e=0;
                           e=e+1;
                           if(e%2==0)
                                 {
                                    $("#twitch-pasek").animate({left: '-150px'});
                                  }
                            $("#twitch-pasek").animate({left: '150px'});
                            var i=document.getElementById('licznik');
                             i.innerHTML = e;
                            });
                        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Here's jsfiddle I created showing my problem. 尽管每次点击都加 1,但变量 e 的显示值仍然为 1。我应该如何构建它才能使其工作?或者也许有一些像 toggle() 函数这样的技巧,但用于动画?

在点击事件外声明e变量,否则每次点击都会被覆盖,永远是return1。请参阅下面的工作片段:

 $(document).ready(function() {
   var e = 0;
   $("#twitch-pasek-przycisk").click(function() {   
     e = e + 1;
     if (e % 2 == 0) {
       $("#twitch-pasek").animate({
         left: '-150px'
       });
     }
     $("#twitch-pasek").animate({
       left: '150px'
     });
     var i = document.getElementById('licznik');
     i.innerHTML = e;
   });
 });
#twitch-pasek {
  position: relative;
  width: 250px;
  margin-left: -150px;
  height: 75px;
  border-radius: 0px 35px 35px 0px;
  background-color: gray;
  background: #2B2B2B;
}
#twitch-pasek-przycisk {
  position: absolute;
  float: right;
  height: 75px;
  width: 75px;
  border: 5px;
  border-radius: 50%;
  background-color: black;
  outline: none;
}
#licznik {
  background-color: black;
  width: 150px;
  height: 50px;
  color: white;
}
#twitch-pasek-przycisk:focus {
  background-color: white;
  border: 0px;
  outline: none;
}
#twitch-kontener {
  position: absolute;
  margin-top: 5px;
  float: right;
  height: 70px;
  margin-left: -10px;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="twitch-pasek">
  <div id="twitch-kontener">
    Informations
  </div>



</div>
<br/>
<button id="twitch-pasek-przycisk"></button>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<span id="licznik"> Counter: </span>

当您点击您的点击事件时 e 每次都会初始化为 0
使用这个

 $(document).ready(function(){
          var e=0;
          $("#twitch-pasek-przycisk").click(function(){
                e=e+1;
                if(e%2==0)
                {
                   $("#twitch-pasek").animate({left: '-150px'});
                }
                $("#twitch-pasek").animate({left: '150px'});
                var i=document.getElementById('licznik');
                i.innerHTML = e;
           });
});