得到这个未定义

时间:2019-09-12 13:14:06

标签: javascript dom this

在下面的代码中,我收到一个错误,无法更改未定义的背景颜色。当我用此代码替换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")
        }
    })

}

1 个答案:

答案 0 :(得分:1)

Arrow function (=>)没有自己的this。在事件处理函数中使用常规函数语法或使用squares[i]

var chosenColor = squares[i].style.backgroundColor;