Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用类在单击时更改背景色_Javascript_Colors - Fatal编程技术网

Javascript 使用类在单击时更改背景色

Javascript 使用类在单击时更改背景色,javascript,colors,Javascript,Colors,这是我的代码: function black(){ document.queryselectoral(“.object”).style.backgroundColor=“黑色”; } 函数red(){ document.queryselectoral(“.object”).style.backgroundColor=“红色”; } 函数蓝(){ document.queryselectoral(“.object”).style.backgroundColor=“蓝色”; } .object{

这是我的代码:

function black(){
document.queryselectoral(“.object”).style.backgroundColor=“黑色”;
}
函数red(){
document.queryselectoral(“.object”).style.backgroundColor=“红色”;
}
函数蓝(){
document.queryselectoral(“.object”).style.backgroundColor=“蓝色”;
}
.object{
宽度:200px;
高度:200px;
背景色:黑色;
利润率:20px;
}
黑色
红色
蓝色
您的问题是返回节点列表,您需要迭代其中的值,更改每个值的背景:

function black(){
document.queryselectoral(“.object”).forEach(v=>v.style.backgroundColor=“black”);
}
函数red(){
document.queryselectoral(“.object”).forEach(v=>v.style.backgroundColor=“红色”);
}
函数蓝(){
document.queryselectoral(“.object”).forEach(v=>v.style.backgroundColor=“blue”);
}
.object{
宽度:200px;
高度:200px;
背景色:黑色;
利润率:20px;
}
黑色
红色
蓝色

这不是一个数组,而是一个@epascarello,你当然是对的。我已经编辑了答案。