vendredi 16 août 2019

Why use "this" with addEventListener [duplicate]

This question already has an answer here:

Can anyone tell me "this" and square[i] different? I don't know how to fix this problem with squares[i] have bug.

colorgame.js:19 Uncaught TypeError: Cannot read property 'style' of undefined at HTMLDivElement. (colorgame.js:19)

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 colorDisplay = document.getElementById("colordisplay");

colorDisplay.textContent = pickedcolor;

for (var i = 0; i < squares.length; i++) {
    squares[i].style.background = colors[i];
    squares[i].addEventListener("click", function () {
        alert(this.style.background);
    })
}


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 colorDisplay = document.getElementById("colordisplay");

colorDisplay.textContent = pickedcolor;

for (var i = 0; i < squares.length; i++) {
    squares[i].style.background = colors[i];
    squares[i].addEventListener("click", function () {
        alert(squares[i].style.background);
    })
}





Aucun commentaire:

Enregistrer un commentaire