for em onload Javascript

Asked

Viewed 139 times

1

Why I don’t 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 turns normal, like this:

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

The problem is he’s not calling the function showSeatStatus(i); at no time.

  • If you give an Alert within the onclick function it alerts? , I believe the problem is that the onclick function is a Switch or it would be waiting for the action of the click, then when it loads the Switch will rotate but if the click is not made will not call the showSeatStatus

1 answer

2


The problem has to do with closures which makes all the functions of click are related to the same variable i, and therefore with its final value.

To circumvent this effect just change var for let, that the variable exists only 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>

  • I was writing about it, but you were faster (and I wouldn’t have written it so well). + 1.

  • It worked, however I did not understand the operation :/, I was researching about clousers and Let, I understood that Let only runs in block scope. but I didn’t understand the clousers in that code.

  • @Nicolasguilhermematheus closure is the mechanism of the function to store the values it needs to later execute, values that only exist at that time, such as the i in showSeatStatus(i);. Remember that when the function runs, a long time later, theoretically the i would no longer exist.

  • @Isac, at first it is not yet clear to me, but you can let me understand with time, I started my studies on JS recently. Thank you for explaining to me how it works, and for the words closure and Let, that has already added an additional knowledge to me, for example, in JS you can assign a value to an undeclared variable and then declare it, that even then the code will work, at runtime the JS sends up all variables.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.