我如何一步通过一个单元格在一个时间使用onclick数组

How do I step though an array one cell at a time using onclick?

本文关键字:一个 时间 onclick 数组 单元格 何一步      更新时间:2023-09-26

我是新的JavaScript,并试图创建一个函数,改变我的HTML文档的背景颜色,每次我点击一个div。我的代码只是循环,虽然我的数组一直到结束,而不是一个循环每次点击我的div。我知道我错过了一些增量每次我点击div,但不能弄清楚什么。在我的HTML文档中我有一个DIV

<div id="autoText" onclick="moveMe()"></div>.

这是目前为止我的JavaScript:

var multipleColors = [];
multipleColors[0] =  "red";
multipleColors[1] =  "blue";
multipleColors[2] =  "yellow";
function moveMe() {
for (i=0; i < multipleColors.length; i++) {
console.log("This is step " + i);
this.document.body.style.backgroundColor=multipleColors[i];
}
}

我真的很感激任何人的建议?

谢谢。

如果您想在到达结束后从开始继续,请使用%(取模)运算符:

var multipleColors = [];
multipleColors[0] =  "red";
multipleColors[1] =  "blue";
multipleColors[2] =  "yellow";
var current = 0;
function moveMe() {
    current++;
    var newIdx = current % multipleColors.length;
    this.document.body.style.backgroundColor = multipleColors[newIdx];
}

不使用循环,而是使用计数器变量,每当单击该元素时,该变量都会增加:

var index = 0;
function moveMe() {
  console.log("This is step " + index);
  this.document.body.style.backgroundColor=multipleColors[index];
  index += 1;
}

如果你想在数组结束后从数组的开头继续,重置变量:

var index = 0;
function moveMe() {
  console.log("This is step " + index);
  this.document.body.style.backgroundColor=multipleColors[index];
  index += 1;
  if (index === multipleColors.length) {
    index = 0;
  }
}

试试这样

var multipleColors = [];
multipleColors[0] =  "red";
multipleColors[1] =  "blue";
multipleColors[2] =  "yellow";
function moveMe() {
    this.document.body.style.backgroundColor=(multipleColors[multipleColors.indexOf(this.document.body.style.backgroundColor)+1])?multipleColors[multipleColors.indexOf(this.document.body.style.backgroundColor)+1]:multipleColors[0];
}

你可以继续在数组中添加更多的颜色。