你好,我是一个自学成才的开发人员,我正在尝试使用jQuery的for()循环,但它似乎不起作用。我试图循环遍历一系列RGB颜色,现在用字符串进行硬编码。以下是我想要完成的内容的片段。我希望每个div都包含不同的内容
http://jsfiddle.net/CleverOscarDev/cyztq6m5/
var squares = $(".squares");
var colors = [
"rgb(255, 0, 0)",
"rgb(0, 255, 0)",
"rgb(0, 0, 255)",
"rgb(255, 0, 0)",
"rgb(255, 0, 0)",
"rgb(255, 0, 0)",
]
for (var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = colors;
}
检查更新的小提琴http://jsfiddle.net/0xdwhsnc/
你错过了索引,而不是颜色使用颜色[i]
for (var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = colors[i];
}
尝试每个循环。 http://jsfiddle.net/cyztq6m5/15/
$(squares).each(function(key, value) {
value.style.backgroundColor = colors[key];
});
如果您的颜色数组的颜色数与具有类正方形的div数相同,则可以执行此操作!
$(".squares").each(function(key, value) {
$(this).css({"background-color" : colors[key]});
});
你有一个简单的错误,colors
是一个数组,而不是一个颜色字符串,所以你应该使用colors[i]
for (var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = colors[i];
}
你也可以为每个人使用jquery
$.each(squares, function(idx, square){
square.style.backgroundColor=colors[idx]
});