使用数组和对象的颜色背景,为可逆的可重复的div

时间:2016-12-25 18:32:10

标签: javascript arrays object

var ar = ["one_in", "two_in", "three_in"];
    var colors = {};
    [ar[0]] = 'blue';
    [ar[1]] = 'green';
    [ar[2]] = 'red';
x = document.getElementsByTagName('DIV');
for (var i = 0 ; i < x.length ; i++ ){
    x[i].style.backgroundColor = colors[x[i].className];
}
.one_in,.two_in{
width:100px;
height:100px;
border:1px solid #000;
}
<div class="one_in"></div><div class="two_in"></div>

为什么不能再次使用,我想让div用各自的颜色和数组和对象中提到的div class进行着色,我知道这是一个简单的问题,可能是一个小错误

https://jsfiddle.net/qothk6g3/3/

1 个答案:

答案 0 :(得分:4)

您在属性前面缺少color,其中数组的项目为property accessor

&#13;
&#13;
var ar = ["one_in", "two_in", "three_in"],
    x = document.getElementsByTagName('DIV'),
    i,
    colors = {};

colors[ar[0]] = 'blue';
colors[ar[1]] = 'green';
colors[ar[2]] = 'red';

for (i = 0 ; i < x.length ; i++) {
    x[i].style.backgroundColor = colors[x[i].className];
}
&#13;
.one_in,.two_in { width:100px; height:100px; border:1px solid #000; }
&#13;
<div class="one_in"></div><div class="two_in"></div>
&#13;
&#13;
&#13;