我正在做一個隨機背景顏色的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>
塊是一個數組,並且您喜歡的對象處理它。嘗試使用for(i = 0; i
HCJ