我想在 <input/>
提交时打乱数组在 JavaScript 中然后吐出 [0]
从数组中放入 ID 为 message
的 div 。但是当我再次按下提交按钮时。我想要[1]
数组的。接下来提交[2]
。只要数组存在,我就想继续下去。然后从 [0]
重新开始.
我希望它如何工作:
HTML:
<form action="" method="post" onsubmit="return submit()">
<input type="submit" id="submit" value="Submit!">
</form>
<div id="message">
JS:
function submit() {
message = ["Message 1","Message 2","Message 3"] // I want more messages than this.
// The shuffle script here.
document.getElementById("message").innerHTML = message;
return false;
}
我已经设置好了数组。但我希望它被打乱,并在第二次提交时吐出另一条消息,这样我就不会收到两次相同的消息。
这个想法只是从数组中获取随机消息,而不会在第二次提交后两次获取相同的消息。
如果您有更好的想法,请告诉我。
最佳答案
您可能希望在函数之前设置一个计数器,然后在函数内部将消息设置到数组中的计数器位置。然后,当你的计数器达到数组的长度时,将计数器重置为 0。类似这样的
var count = 0;
var message = ["Message 1","Message 2","Message 3"] // probably want this outside your submit function so its not declared everytime the function is called
function submit() {
// The shuffle script here.
document.getElementById("message").innerHTML = message[count];
if ((count + 1) >= message.length) {
count = 0; // if the count + 1 is more than or equal to the array length then reset the counter
} else {
count += 1; // increase the count
}
return false;
}
关于JavaScript 在提交时随机排列数组并进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30780598/