2016-12-25 383 views
4

颜色背景

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>

为什么不是这个工作了,我要让股利彩色各自的颜色,并为阵列中提到divclass和对象,我知道它给你一个简单的问题,可能是一个小的失误

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

回答

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]; 
 
}
.one_in,.two_in { width:100px; height:100px; border:1px solid #000; }
<div class="one_in"></div><div class="two_in"></div>

+0

妈的,打我再次感谢 – bob0the0mighty

+0

@nina, – Anjali

+0

但不工作https://jsfiddle.net/qothk6g3/ – Anjali