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
class
为 div 着色,我知道它很简单问题给你,可能是个小错误
最佳答案
您在属性前面缺少 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];
}
.one_in,.two_in { width:100px; height:100px; border:1px solid #000; }
<div class="one_in"></div><div class="two_in"></div>
关于javascript - 使用 array 和 object 为可逆可重复 div 着色背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41323573/