我在代码中使用“ this”关键字,并决定将其替换为squares [i]。当我单击div时,控制台向我显示错误消息:“无法读取未定义的属性”。
var colors=[
"rgb(255, 0, 0)",
"rgb(255, 255, 0)",
"rgb(0, 255, 0)" ,
"rgb(0, 255, 255)",
"rgb(0, 0, 255)",
"rgb(255, 0, 255)" ];
var squares=document.querySelectorAll(".square");
var pickedColor=colors[3];
var display=document.getElementById("colorDisplay");
display.textContent=pickedColor;
for(var i=0;i<squares.length;i++){
//ADD INITIAL COLORS TO SQUARES
squares[i].style.backgroundColor=colors[i];
//ADD EVENTLISTENERS TO SQUARES
squares[i].addEventListener("click",function(){
console.log(squares[i].style.backgroundColor);
});
}
//__________________________________________________________________________
//This is the correct version of the code
var colors=[
"rgb(255, 0, 0)",
"rgb(255, 255, 0)",
"rgb(0, 255, 0)" ,
"rgb(0, 255, 255)",
"rgb(0, 0, 255)",
"rgb(255, 0, 255)" ];
var squares=document.querySelectorAll(".square");
var pickedColor=colors[3];
var display=document.getElementById("colorDisplay");
display.textContent=pickedColor;
for(var i=0;i<squares.length;i++){
//ADD INITIAL COLORS TO SQUARES
squares[i].style.backgroundColor=colors[i];
//ADD EVENTLISTENERS TO SQUARES
squares[i].addEventListener("click",function(){
console.log(this.style.backgroundColor);
});
}
我添加了两个版本的代码。第一个是不正确的,而第二个是正确的。