首页 > 解决方案 > Jquery自动增量值并检测重置

问题描述

我从值 i=0 开始,最大值为 4,当脚本检测到与 4 相同的值时,必须重新启动或将“i”的值重置为 0 作为默认值

i = 0;

function loading() {

  if (i == 4) {
    i = 0;
  }

  jQuery("#text").show(1000).hide(1000, function() {
    reloading();
  });
}


function reloading() {
  setInterval("loading()", 2000);
  alert("ok" + i);
  i++;
}


loading();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" style="position:relative;width:150px;height:150px;background-color:red;display:none;"></div>

我尝试显示 div 4 次并重置为 0 并开始其他时间 0、1、2、3,并重置 0 并开始其他时间,但不起作用,我不知道为什么会发生这种情况,我认为代码没关系,但肯定有什么不好的

感谢高级版的帮助

标签: javascriptjquerysettimeoutsetinterval

解决方案


问题是当您调用函数loading()以启动从 1 开始的动画变量i值时,而不是 0,因此它只运行 3 次,然后重置为 0。(因为 3 次迭代后i变为 4)

所以增加 4 到 5 英寸if(i==4){,你会很高兴

工作片段: -

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" style="position:relative;width:150px;height:150px;background-color:red;display:none;"></div>

<script>
    i=0;
    $(document).ready(function(){
        loading();
    });
    function loading(){
      if(i==5){
        i=0;
      }
      jQuery("#text").show(1000).hide(1000,function(){reloading();});
    }
    function reloading(){
      setInterval("loading()",2000);
      alert("ok"+i);
      i++;
    }
</script>

推荐阅读