JavaScript 在提交时随机排列数组并进行计数

标签 javascript html arrays

我想在 <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/

相关文章:

javascript - 确定浏览器是否支持 iFrame 中的 javascript?

php - Ajax请求php文件输出mysql数据

java - 获取所有受马影响的字段作为点数组

javascript - 是否有任何高阶函数可以从 javascript 中的对象数组返回对象?

javascript - 如何使 jQuery 成为目标并将插件调用附加到数百个 CSS ID 的末尾有一个 ID 号?

javascript - 从 Angular 12 更新到 13 时如何修复 'require() of ES Module not supported' 错误?

javascript - 使用 ember js 通过收件箱/发件箱单个应用程序发送电子邮件

javascript - 无法将文本添加到幻灯片 li 元素中

html - 如何消除 SVG 图层左侧的不良抗锯齿或混合效果?

c# - 数组到 XML 的 .NET 序列化。如何为数组类型设置别名?