我遇到了这个问题。每次弹出窗口加载时,我都想从数组中选择随机单词。但是这个词没有改变。我总是得到如下结果:
(march, march, march.. january, january, january, january, january)...
它只是选择随机月份,然后在每个循环中使用它。我想让它在每个循环中都是随机的。有人可以帮帮我吗?
var i;
for (i = 0; i < 5; i++) {
$("#notification").fadeIn("slow").delay(1000).fadeOut("slow");
var myArray = ['January', 'February', 'March'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
document.getElementById("notification").innerHTML = rand;
}
//$("#notification").append(rand);
#notification {
position: fixed;
bottom: 5px;
left: 5px;
width: 170px;
/* set to 100% if space is available */
height: 70px;
z-index: 105;
text-align: center;
font-weight: normal;
font-size: 12px;
color: white;
background-color: #FF7800;
box-shadow: 0 0 10px #222;
padding: 5px;
opacity: 0.7;
filter: alpha(opacity=70);
/* For IE8 and earlier */
}
#notification span.dismiss {
border: 2px solid #FFF;
padding: 0 5px;
cursor: pointer;
float: right;
margin-right: 10px;
}
#notification a {
color: white;
text-decoration: none;
font-weight: bold
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notification" style="display: none;">
<span class="dismiss"><a title="dismiss this notification">X</a></span>
</div>
JSfiddle link
最佳答案
您的 for
循环在动画开始之前立即完成,因此您只能看到最后生成的随机值。
相反,您每次都需要等待动画完成,然后再进行下一次迭代。这可以通过 fadeOut
的回调参数来实现:
var myArray = ['January', 'February', 'March'];
(function loop(i) {
if (i >= 5) return; // all iterations have been completed
var rand = myArray[Math.floor(Math.random() * myArray.length)];
document.getElementById("notification").textContent = rand;
// Use callback argument of fadeOut to chain to next iteration
// when the animation is complete
$("#notification").fadeIn("slow").delay(1000).fadeOut("slow", loop.bind(null, i+1));
})(0); // Execute the loop function immediately with i = 0
#notification {
position: fixed;
bottom: 5px;
left: 5px;
width:170px; /* set to 100% if space is available */
height: 70px;
z-index:105;
text-align:center;
font-weight:normal;
font-size:12px;
color:white;
background-color:#FF7800;
box-shadow:0 0 10px #222;
padding:5px;
opacity: 0.7;
filter: alpha(opacity=70); /* For IE8 and earlier */
}
#notification span.dismiss {
border:2px solid #FFF;
padding:0 5px;
cursor:pointer;
float:right;
margin-right:10px;
}
#notification a {
color:white;
text-decoration:none;
font-weight:bold
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notification" style="display: none;">
<span class="dismiss"><a title="dismiss this notification">X</a></span>
</div>
关于JavaScript循环从数组中随机选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51360820/