在下面的代码中,我收到一个错误,无法更改未定义的背景颜色。当我用这个代码替换 squares[i] 时。我不明白为什么?
var colors =[
"rgb(255, 0, 0)",
"rgb(255, 255, 0)",
"rgb(0, 255, 255)",
"rgb(0, 0, 255)",
"rgb(0, 255, 0)",
"rgb(255, 0, 255)"
];
var colorPicked = colors[3];
var head = document.querySelector("#color");
head.textContent = colorPicked;
var squares = document.querySelectorAll(".square");
for(let i=0;i<squares.length;i++){
//to apply colors array on the square
squares[i].style.backgroundColor = colors[i];
//adding click event listener to square
squares[i].addEventListener("click",()=>{
var chosenColor = this.style.backgroundColor;
if(chosenColor == colorPicked){
alert("correct")
}else{
alert("wrong")
}
})
}
小怪兽爱吃肉
相关分类