当我点击圆圈时,如何使用Javascript使其改变颜色?此外,如果所有圆圈都是红色,如何使文本显示?我

当我点击圆圈时,如何使用Javascript使其改变颜色?此外,如果所有圆圈都是红色,如何使文本显示?我,javascript,html,Javascript,Html,函数nextColor(inputID,newColor){ 让输入=document.querySelector(“#”+inputID) 让color=input.getAttribute(“填充”) 如果(color=“red”){ newColor=“蓝色”; }否则如果(color=“橙色”){ newColor=“绿色”; }否则如果(color=“green”){ newColor=“红色”; } 返回新颜色; } 功能标识(新颜色){ 如果(newColor=“红色”){ doc

函数nextColor(inputID,newColor){
让输入=document.querySelector(“#”+inputID)
让color=input.getAttribute(“填充”)
如果(color=“red”){
newColor=“蓝色”;
}否则如果(color=“橙色”){
newColor=“绿色”;
}否则如果(color=“green”){
newColor=“红色”;
}
返回新颜色;
}
功能标识(新颜色){
如果(newColor=“红色”){
document.querySelector(“#messageOutput”).innerHTML=“您得到了相同的颜色”;
}
}
函数颜色更改(事件){
让元素=event.target;
setAttribute(“fill”,nextColor('circle1',newColor));
身份(新颜色);
返回;
}

变色游戏。
变色游戏

目标是使所有的圆都具有相同的颜色。当你点击一个圆圈时,它会改变颜色
红色圆圈变成蓝色,
蓝色圆圈变成橙色,
橙色圆圈变成绿色,
绿色圆圈变成红色
您必须使用 所有圆圈的同一事件侦听器。当圆圈颜色相同时,在svg图形下方显示消息“颜色相同”。


您的代码中有很多问题

关于如何编码的一些建议:

  • 对于静态不可变对象,请使用const:nextColor不需要函数
  • 传递参数时,尝试传递函数所需的最小数据量:例如,identity不需要参数
  • 更明智地使用
    querySelector
    。请阅读这篇文章,了解Web API()函数的优点/缺点
请试一试

const nextColor={
红色:“蓝色”,
蓝色:“橙色”,
橙色:“绿色”,
绿色:“红色”
}
函数标识(){
document.querySelector(“#messageOutput”).innerHTML=
document.querySelector(“#圈1”).getAttribute(“填充”)===
document.querySelector(“#圈2”).getAttribute(“填充”)&&
document.querySelector(“#圈1”).getAttribute(“填充”)===
document.querySelector(“#圈3”).getAttribute(“填充”)?
“您得到了相同的颜色”:”;
}
函数颜色更改(事件){
让元素=event.target;
element.setAttribute(“fill”,nextColor[element.getAttribute(“fill”));
身份();
返回;
}

变色游戏。
变色游戏

目标是使所有的圆都具有相同的颜色。
当你点击一个圆圈时,它会改变颜色
红色圆圈变成蓝色,
蓝色圆圈变成橙色,
橙色圆圈变成绿色
绿色的圆圈变成红色
您将对所有圆圈使用相同的事件侦听器。 当圆圈颜色相同时,显示消息 svg图形下方的“所有颜色相同”。


stackoverflow不是这样工作的,请尝试自己解决问题,如果您有任何问题,我们将非常乐意提供帮助。祝你好运

let colorChangesTo = {
  red: "blue",
  blue: "orange",
  orange: "green",
  green: "red"
}

let message = "All the same color";
let output = document.querySelector("#messageOutput");

function colorChange(event) {
  let color = event.target.getAttribute("fill");
  event.target.setAttribute("fill", colorChangesTo[color]);
  output.innerText = isColorsTheSame() ? message : "";
}

let isColorsTheSame = () => {
  let circles = document.querySelectorAll("circle");
  let colors = [];
  [...circles].forEach(x => {
    colors.push(x.getAttribute("fill"))
  });
  let isTheSame = (currentVal) => currentVal === colors[0];
  return colors.every(isTheSame) ? true : false;
}