未捕获类型错误: 无法设置未定义的属性'background'



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

"未捕获的类型错误: 无法设置未定义的属性'背景'"

这是我的 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] + ")";
}

相关内容

最新更新