未捕获的TypeError:无法设置undefined的属性“background”

时间:2015-04-17 11:54:30

标签: javascript html arrays google-chrome styles

我即将制作随机背景色javascript代码。因此,当您刷新页面时,所有元素的背景颜色都会发生变化,但在Chrome中,我收到了错误:

  

“未捕获的TypeError:无法设置未定义的属性'background'”

这是我的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>

               

1 个答案:

答案 0 :(得分:2)

您正在使用for ... in迭代块,这也会导致您遍历&#34;长度&#34;属性。

更好的方法:

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] + ")";
}