javascript - 尝试设置超时来显示和隐藏球

标签 javascript jquery html css asynchronous

我试着写了一个程序来练习我的js技能。有 3 个球,一开始它们是隐藏的。我希望 ball_1 先出现,1 秒后,ball_1 消失。接下来,ball_2 出现并在 1 秒后消失;同样的逻辑也适用于 ball_3。当我运行我的代码时,前两个球不会隐藏。我不确定出了什么问题。下面的代码是我写的html、css、js代码。希望有人能帮助我。先感谢您。

$(document).ready(function() {
  var notes = ['ball_1', 'ball_2', 'ball_3'];
  for (i = notes.length; i > 0; i--) {
    var note = notes.shift();
    $('#' + note).addClass('shown');
    setTimeout(function() {
      $('#' + note).removeClass('shown');
    }, 1000);
  }
});
#ball_1 {
  width: 10px;
  height: 10px;
  background: #000000;
  border: 2px solid #ccc;
  border-radius: 50%;
}
#ball_2 {
  width: 10px;
  height: 10px;
  background: #0000FF;
  border: 2px solid #ccc;
  border-radius: 50%;
}
#ball_3 {
  width: 10px;
  height: 10px;
  background: #7FFF00;
  border: 2px solid #ccc;
  border-radius: 50%;
}
#ball_1,
#ball_2,
#ball_3 {
  width: 10px;
  height: 10px;
  border: 2px solid #ccc;
  border-radius: 50%;
}
.not_shown {
  display: none;
}
.shown {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<div id="ball">
  <div id="ball_1" class="not_shown"></div>
  <div id="ball_2" class="not_shown"></div>
  <div id="ball_3" class="not_shown"></div>
</div>

最佳答案

通常,在使用 for 循环进行迭代时永远不要修改数组。 shift 方法将从数组中删除第一项,从而修改它的长度。而是这样做:

$(document).ready(function() {
  var notes = ['ball_1','ball_2','ball_3'];
  var i; // You were declaring "i" in global namespace before.  Don't do that.
  for(i = 0; i < notes.length; i++){
    var note = notes[i];
    $('#' + note).addClass('shown');
      setTimeout(function() {
        $('#' + note).removeClass('shown');
      },1000);
    }
});

您还可以从我的注释中看到您在全局命名空间中定义了“i”。这样做从来都不好,所以如果使用“var”,请始终确保在功能 block 的开头定义变量。

编辑:漏掉了一个分号

EDIT2:完全错过了我需要改变循环条件的地方。

关于javascript - 尝试设置超时来显示和隐藏球,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40714718/

相关文章:

javascript - jQuery/JS/PHP - 仅在提交后禁用表单和提交按钮

javascript - 当我向下滚动一定数量时,我试图让一个 div 出现?

javascript - 为什么 "new function"调用该函数?

javascript - 如何在javascript中禁用标签标签

javascript - 列表及其滚动条的不同 z-index

javascript - 将输入限制为在 IE 中使用大写字符的特定正则表达式

添加类后 jQuery 单击事件不起作用

javascript - 从 Javascript 元素列表中检查哪个元素导致事件

jquery - 复选框 jQuery .on() 无法在 SonataAdminBundle 2.3 和 Symfony 2.3 中工作

javascript - 使用 JS 在 DOM 内部创建元素