2015-04-17 107 views
0

我正在做一個隨機背景顏色的JavaScript代碼。所以,當你刷新頁面,所有元素的背景顏色會改變,但在Chrome中,我得到了一個錯誤:未捕獲TypeError:無法設置未定義的屬性'背景'

"Uncaught TypeError: Cannot set property 'background' of undefined"

這裏是我的JavaScript和HTML:

var colors = [ 
 
    [ 
 
     [65], [131], [215] 
 
    ], [ 
 
     [217], [30], [24] 
 
    ], [ 
 
     [245], [215], [110] 
 
    ], [ 
 
     [135], [211], [124] 
 
    ] 
 
]; 
 
//Getting a random color 
 
var random = Math.floor(Math.random() * 4); 
 

 
var block = document.getElementsByClassName('block'); 
 
var obj; 
 
for (obj in block) { 
 
    if (block.hasOwnProperty(obj)) { 
 

 
     block[obj].style.background = 
 
      "rgb" + "(" + colors[random][0] + ", " + colors[random][1] + ", " + colors[random][2] + ")"; 
 
    } 
 
} 
 

 

 
document.getElementById('body').style.background = "rgb" + "(" + colors[random].r + ", " + colors[random].g + ", " + colors[random].b + ")";
<a href="#"> 
 
<li class="block block1"> 
 
\t <i class="icon-vcard"></i> 
 
\t <h3>Contact us</h3> 
 
\t <content> 
 
\t <h3>Contact us</h3> 
 
\t <p> 
 
\t Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</p> 
 
\t </content> 
 
</li> 
 
</a> 
 
<a href="#"> 
 
\t <li class="block block2"> 
 
\t <i class="icon-users"></i> 
 
\t <h3>Staff</h3> 
 
\t <content> 
 
\t <h3>Staff</h3> 
 
\t <p> 
 
\t Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</p> 
 
\t </content> 
 
</li> 
 
</a> 
 
<a href="#"> 
 
\t <li class="block block3"> 
 
\t <i class="icon-wrench"></i> 
 
\t <h3>Tools</h3> 
 
\t <content> 
 
\t <h3>Tools</h3> 
 
\t <p> 
 
\t Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</p> 
 
\t </content> 
 
</li> 
 
</a> 
 
<a href="#"> 
 
\t <li class="block block4"> 
 
\t <i class="icon-info"></i> 
 
\t <h3>About us</h3> 
 
\t <content> 
 
\t <h3>About us</h3> 
 
\t <p> 
 
\t Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</p> 
 
\t </content> 
 
</li> 
 
</a> 
 

 
</ul> 
 

 
      

+1

塊是一個數組,並且您喜歡的對象處理它。嘗試使用for(i = 0; i HCJ

回答

2

你使用for ... in迭代塊,這也會導致您遍歷「length」屬性。

更好的方法:

var blocks = document.getElementsByClassName('block'); 

for (var i=0;i<blocks.length;i++) { 
     blocks[i].style.background = 
      "rgb" + "(" + colors[random][0] + ", " + colors[random][1] + ", " + colors[random][2] + ")"; 
} 
+0

只是爲了解釋爲什麼'length'被捕獲,還有屬性:'document.getElementsByClassName'返回數組類對象'HTMLCollection'而不是真正的數組;對於標準數組for..in將正確返回值(直到某些屬性將被添加到那裏),但這是不好的方法。 –

相關問題