【问题标题】:getting this as undefined [duplicate]将此作为未定义[重复]
【发布时间】:2020-01-14 09:10:25
【问题描述】:

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

}

【问题讨论】:

    标签: javascript dom this


    【解决方案1】:

    Arrow function (=&gt;) 没有自己的this。要么使用普通函数语法,要么在事件处理函数中使用squares[i]

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

    【讨论】:

      猜你喜欢
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      相关资源
      最近更新 更多