如何使用onclick一次遍历一个单元格的数组?

时间:2014-05-12 06:46:50

标签: javascript onclick

我是JavaScript的新手,我正在尝试创建一个函数,每次单击DIV时都会更改HTML文档的背景颜色。我的代码只是循环我的数组一直到最后,而不是每次点击我的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];
}
}

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

感谢。

3 个答案:

答案 0 :(得分:1)

如果你想在结束之后从头开始继续,请使用%(modulo)运算符:

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];
}

答案 1 :(得分:0)

不使用循环,而是使用在单击元素时增加的计数器变量:

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;
  }
}

答案 2 :(得分:-1)

尝试这样的事情

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];

}

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

<强> DEMO

相关问题