Uncaught TypeError: Cannot set property 'background' of undefined

Uncaught TypeError: Cannot set property 'background' of undefined

我即将制作一个随机背景色 javascript 代码。所以当你刷新页面时,所有元素的背景颜色都会改变,但在 Chrome 中,我得到一个错误:

"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">
 <i class="icon-vcard"></i>
 <h3>Contact us</h3>
 <content>
 <h3>Contact us</h3>
 <p>
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</p>
 </content>
</li>
</a>
<a href="#">
 <li class="block block2">
 <i class="icon-users"></i>
 <h3>Staff</h3>
 <content>
 <h3>Staff</h3>
 <p>
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</p>
 </content>
</li>
</a>
<a href="#">
 <li class="block block3">
 <i class="icon-wrench"></i>
 <h3>Tools</h3>
 <content>
 <h3>Tools</h3>
 <p>
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</p>
 </content>
</li>
</a>
<a href="#">
 <li class="block block4">
 <i class="icon-info"></i>
 <h3>About us</h3>
 <content>
 <h3>About us</h3>
 <p>
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</p>
 </content>
</li>
</a>

</ul>

               

您正在使用 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] + ")";
}