0

Trying to add different background colors to divs using a for loop. I stored all the colors in 20 variables and I want each of the 20 divs to have their own color. I'm trying to set it like this "background-color":(bar+i), but that does that work. It works if I just pass one variable like bar1. What am I doing wrong? Any help is greatly appreciated.

var bar1 = "#afb626";
var bar2 = "#5b590a";
var bar3 = "#b44708";
var bar4 = "#950000";
var bar5 = "#eb9f9f";
var bar6 = "#246d13";
var bar7 = "#afb626";
var bar8 = "#a60046";
var bar9 = "#733702";
var bar10 = "#d1570d";
var bar11 = "#afb626";
var bar12 = "#5b590a";
var bar13 = "#b44708";
var bar14 = "#950000";
var bar15 = "#eb9f9f";
var bar16 = "#246d13";
var bar17 = "#afb626";
var bar18 = "#a60046";
var bar19 = "#733702";
var bar20 = "#afb626";


for (var i = 0; i < 20; i++) {
    $('<div/>', { id: 'foo'+i,}).appendTo('body');
      $("#foo"+i).css({"background-color":(bar+i),"height": "100%", "width": screenWidth, "float": "right"});
}
4

3 回答 3

3

Use an array instead:

var bars = ["#afb626", "#5b590a", ...];

for (var i = 0, z = bars.length; i < z; i++) {
    $('<div/>', {
        id: 'foo' + i
    }).css({
         backgroundColor: bars[i],
         height: "100%",
         width: screenWidth,
         float: "right"
    }).appendTo('body');
}
于 2013-07-08T12:14:44.187 回答
1
(bar+i)

应该

(window["bar"+i])
于 2013-07-08T12:11:30.340 回答
0

您的代码中存在一些问题。我为你做了一个简单的例子

JSFiddle 演示链接

var bar = ["#afb626", "#5b590a", "#b44708", "#950000", "#eb9f9f", "#246d13", 
              "#afb626", "#a60046", "#733702", "#d1570d", "#afb626", "#5b590a", 
              "#b44708", "#950000", "#eb9f9f", "#246d13", "#afb626", "#a60046", 
              "#733702", "#afb626"];


for (var i = 0; i < bar.length; i++) {
    $('<div/>', {id: 'foo' + i})
       .css({
        "background-color": bar[i],
        "height": "100px", 
        "width": $(window).width(), 
        "float": "left"
    }).appendTo('body');
}

问题

您应该为您的项目使用数组。使负载更有意义

for (var i = 0; i < 20; i++) {
    $('<div/>', { id: 'foo'+i, /* < you shouldn't have a comma here */ }).appendTo('body');
      $("#foo"+i).css({"background-color":(bar+i),"height": "100%", "width": screenWidth, "float": "right"});
}

// What is screenWidth?
// You shouldn't create your element - append it to body then reselect it?? 
于 2013-07-08T12:17:31.993 回答