将其视为未定义
getting this as undefined
在下面的代码中,我收到无法更改未定义背景颜色的错误。当我用这段代码替换 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")
}
})
}
Arrow function (=>)
没有自己的 this
。使用普通函数语法或在事件处理函数中使用 squares[i]
:
var chosenColor = squares[i].style.backgroundColor;
在下面的代码中,我收到无法更改未定义背景颜色的错误。当我用这段代码替换 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")
}
})
}
Arrow function (=>)
没有自己的 this
。使用普通函数语法或在事件处理函数中使用 squares[i]
:
var chosenColor = squares[i].style.backgroundColor;