javascript - document.getElementsByClassName("changecolor").style.backgroundColor 不起作用
问题描述
我不知道为什么这个特殊功能不起作用,我尝试了不同的东西,问朋友,谷歌搜索,但我只是不确定为什么它根本不起作用。
我有一个创建随机颜色的函数,以及一个在按下按钮时将背景色更改为随机生成的颜色的函数。
这工作正常:
function randomColors() {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
function randomize() {
document.body.style.backgroundColor = randomColors();
}
randomize();
我使用时它仍然可以正常工作
document.getElementById("change").style.backgroundColor = randomColors();
但是我想一次更改身体的背景颜色和 2 个按钮,所以我正在使用
function randomColors() {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
function randomize() {
document.getElementsByClassName("changecolor").style.backgroundColor = randomColors();
}
randomize();
机身和按钮的颜色根本不会改变。元素确实有类changecolor。
function randomColors() {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
function randomize() {
document.getElementsByClassName("changecolor").style.backgroundColor = randomColors();
}
randomize();
<a class="twittershare" href="https://twitter.com/intent/tweet?text=Hello%20world" target="_blank"><button class="btn btn-primary changecolor"><i class="fa fa-twitter-square"></i></button></a>
编辑,感谢指导我修复的评论。以下代码使它对我有用:
function randomColors() {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
function randomize() {
let rcolor = document.getElementsByClassName("changecolor");
let randomc = randomColors();
for(let i = 0; i < rcolor.length; i++) {
rcolor[i].style.backgroundColor = randomc;
}
}
randomize();
解决方案
推荐阅读
- c# - 为 asp.net 核心 web api 中的方法编写测试
- node.js - 我来自 Nodejs 后端的 Fetch 请求有什么问题?
- tensorflow - 在 edward2 和 tensorflow2 中用 beta 预测二项式的 p
- regex - 在 Tcl 中,如何删除左侧的所有零但右侧的零应该保留?
- elasticsearch - 弹性搜索主节点不相互通信
- python - 在 Python 上编写非 Ascii 文本
- javascript - 用户输入无法识别点击自动完成
- javascript - React Native Flex-Wrap 不会将文本换行或挤压到屏幕的一侧
- php - 这个带有左连接的 laravel 查询有什么问题?
- python - 为什么我的 python 程序找不到模块,尽管我的设置是正确的?