ReferenceError: button is not defined

0

I wanted to know what the error is in this code. The button is set, yes, and the console is pointing to 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>
    
asked by anonymous 05.08.2017 / 22:50

1 answer

1

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

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

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

And if the window.onload has not yet run then the variable botao does not even exist.

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

To correct, you must pass the code block into window.onload and  change the setting of click in 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>
    
05.08.2017 / 23:24