我试着写了一个程序来练习我的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/