gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot set property 'background' of undefined

转载 作者:行者123 更新时间:2023-12-02 16:15:10 25 4
gpt4 key购买 nike

我即将制作一个随机背景颜色的 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 迭代 block ,这也会导致您迭代“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] + ")";
}

关于javascript - 未捕获的类型错误 : Cannot set property 'background' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29698466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com