HTML
<div class="one_in"></div>
CSS
.one_in{
width:100px;
height:100px;
border:1px solid #000;
}
JS
var ar = ["one_in", "two_in", "three_in"];
var colors = {
ar[0]: 'blue',
ar[1]: 'green',
ar[2]: 'red'
};
x = document.getElementsByClassName('one_in');
for (var i = 0 ; i < x.length ; i++ ){
x[i].style.backgroundColor = colors[x[i].className];
}
如何在对象中使用数组ar
的值"one_in", "two_in", "three_in"
,以便我的div在blue
green
red
分别自动着色
http://www.w3schools.com/code/tryit.asp?filename=FAYMJN2T8KU2
答案 0 :(得分:2)
你必须用[ ]
包装它。
var colors = {
[ar[0]]: 'blue',
[ar[1]]: 'green',
[ar[2]]: 'red'
};