for JavaScript onload

1

What is the reason why I do not get to call the function showSeatStatus(i); ?

window.onload = function() {
    //Conecta os eventos de imagem de poltrona
    for (var i = 0; i < tamanhoMatriz; i++) {
        document.getElementById("acento"+i).onclick = function(evt) { //ELE PASSA AQUI
            showSeatStatus(i); // ELE NÃO PASSA AQUI
        };
    }
};

If I do it without it, it runs normal, like this:

 document.getElementById("acento"+0).onclick = function(evt) {
            showSeatStatus(0);
        };

The problem is that it is not calling the showSeatStatus(i); function at any time.

    
asked by anonymous 19.07.2017 / 03:16

1 answer

2

The problem has to do with closures that makes all functions of click are related to the same variable i , and so with their final value.

To work around this effect, just switch var to let , which forces the variable to only exist in that block, which was one of the ideas behind this new syntax:

for (let i = 0..

Example:

const tamanhoMatriz = 4;

window.onload = function() {
  //Conecta os eventos de imagem de poltrona
  for (let i = 0; i < tamanhoMatriz; i++) {
    document.getElementById("acento" + i).onclick = function(evt) { //ELE PASSA AQUI
      showSeatStatus(i); // ELE NÃO PASSA AQUI
    };
  }
};

function showSeatStatus(indice){
  console.log("Status em " + indice);
}
<div id="acento0">div1</div>
<div id="acento1">div2</div>
<div id="acento2">div3</div>
<div id="acento3">div4</div>
    
19.07.2017 / 13:41