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
进行着色,我知道这是一个简单的问题,可能是一个小错误
答案 0 :(得分:4)
您在属性前面缺少color
,其中数组的项目为property accessor。
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;