2016-12-25 215 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