如果有人有更好的想法 - 我愿意找出来。
代码为here
for color in colors {
function button_click() {
可能甚至是调用函数的错误方法?
答案 0 :(得分:3)
根据我的理解,您希望在点击时更改框的颜色,并且每次单击阵列中的下一个颜色时都会显示。
这是一个简单的实现:
var colors = ["red","blue","green","yellow","purple"];
var i = 0;
var selectedColor;
function button_click() {
selectedColor = colors[i];
document.getElementById("box").style.backgroundColor = selectedColor;
i++;
if(i > colors.length)
i = 0;
}

div#box
{
width:100px;
height:100px;
background-color: white;
border-color: black;
border-style: solid;
border-width: 1px 1px 1px 1px;
}

<div id="box" onclick="button_click();"></div>
&#13;
i是一个变量,每次单击从数组中获取下一个颜色值的框时会递增,当计数器超过颜色数时,它会重置为0(第一种颜色)
答案 1 :(得分:1)
请尝试以下示例:
var colors = ["red","blue","green","yellow","purple"];
var index = 0;
function button_click() {
index = (index + 1) % colors.length;
document.getElementById("box").style.backgroundColor = colors[index];
}
div#box
{
width:100px;
height:100px;
background-color: white;
border-color: black;
border-style: solid;
border-width: 1px 1px 1px 1px;
}
<div id="box" onclick="button_click();"></div>
答案 2 :(得分:0)
我喜欢所有答案,有些非常好,有一两行代码。
这是一个不使用全局var index
这将始终有效,您需要一个循环列表
编辑:白色为默认值,第一种颜色如评论中所述
var colors = ["white","red","blue","green","yellow","purple"];
function button_click() {
var box = document.getElementById("box");
var background_color = box.style.backgroundColor;
var i = colors.indexOf(background_color);
if (i === colors.length-1) {
i = -1;
}
box.style.backgroundColor = colors[i+1];
}
答案 3 :(得分:0)
你走了:
var colors = ["red","blue","green","yellow","purple"],
currentColorIndex = 0;
function button_click() {
document.getElementById("box").style.backgroundColor
= colors[currentColorIndex];
currentColorIndex = (currentColorIndex + 1) % colors.length;
}
您似乎有一些编程经验。我建议你拿一本关于javascript的书。即使是一周的阅读并习惯了语法也会让你走得更远。
如果您关心全局命名空间,那么这个:
Square = (function () {
"use strict";
var colors = ["white", "red","blue","green","yellow","purple"],
currentColorIndex = 0,
squareElement,
initialize = function ()
{
squareElement = document.getElementById("box");
},
clickHandler = function () {
currentColorIndex = (currentColorIndex + 1) % colors.length;
squareElement.style.backgroundColor = colors[currentColorIndex];
};
return {
initialize: initialize,
clickHandler: clickHandler
};
}());
Square.initialize();
<div id="box" onclick="Square.clickHandler()"></div>