Referenceerror: boot is not defined

Asked

Viewed 180 times

0

I wanted to know what is the error in this code. The button is set, yes, and the console pointing this error.

    <script type="text/javascript">
        window.onload = function() {
        var botao = document.getElementsByTagName('button');
            function funcaoAuxiliar(j) {
                alert('Você clicou o botão ' + j);
            };
        }; 
    for (var i=0; i<botao.length; i++) {
        botao[i].onclick = funcaoAuxiliar(i);
    }
    </script>

        <button type="button">botao0</button>
        <button type="button">botao1</button>
        <button type="button">botao2</button>
        <button type="button">botao3</button>
        <button type="button">botao4</button>
        <button type="button">botao5</button>
  • Why the for is out of the window.onload? In fact, do botao[i].onclick = funcaoAuxiliar(i) will not work because you are running the function instead of assigning it to the event.

1 answer

1


The error that appears to you is because the button clicks assignment code is done before the window.onload, this:

for (var i=0; i<botao.length; i++) {
    botao[i].onclick = funcaoAuxiliar(i);
}

Because it’s out of the window.onload, that will only run when the page is fully loaded.

What if the window.onload did not run then the variable botao doesn’t even exist.

Besides botao[i].onclick = funcaoAuxiliar(i); was calling the function instead of just assigning it to the onclick.

To fix you have to pass the code block inside the window.onload and change the definition of click in the for:

window.onload = function() {
  var botao = document.getElementsByTagName('button');

  for (let i = 0; i < botao.length; i++) { //com let i, em vez de var i
    botao[i].onclick = function() { //agora já não precisa do parametro
      alert('Você clicou o botão ' + i);
    };
  }
};
<button type="button">botao0</button>
<button type="button">botao1</button>
<button type="button">botao2</button>
<button type="button">botao3</button>
<button type="button">botao4</button>
<button type="button">botao5</button>

  • So every time I do this -> var X = Function(b,h); I’m assigning the function, and without the parameter, I’m just calling it ?

  • @Fernando var x = function(a,b){... }; is assigning the function. var x = nomeDaFuncaoJaFeita(a,b); is calling and keeping in x the result of the function.

Browser other questions tagged

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