0

 <button id="rock" class="tools">Rock</button>
 <button id="paper" class="tools">Paper</button>
 <button id="scissor" class="tools">Scissor</button>

I am trying to get a random button id name and has the following codes

var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;

for(var i = 0; i < buttonsCount; i++) {
 buttons[i].onclick = function() {
  console.log(this.id);
 }; 
}

But the JSHint validator says Don't make functions within a loop. (http://jshint.com/docs/options/#loopfunc)

Please note that I want to fix this in plain JavaScript (no other frameworks). Does anyone here know how I get this done?

Kyll
  • 7,036
  • 7
  • 41
  • 64

2 Answers2

1

The warning is trying to prevent you from running into problems like JavaScript closure inside loops – simple practical example (which is so common it has about 1800 duplicates or related questions on SO alone).

Fortunately your actual code is not affected by this problem, which means we can pull the function out of the loop. This also fixes the JSHint warning:

var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
var handler = function () {
    console.log(this.id);
};

for (var i = 0; i < buttonsCount; i++) {
    buttons[i].onclick = handler;
}
Community
  • 1
  • 1
melpomene
  • 84,125
  • 8
  • 85
  • 148
0

i<=buttonsCount should be i<buttonsCount

var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;

for(var i = 0; i < buttonsCount; i++) {
    buttons[i].onclick = function() {
        console.log(this.id);
    }   
}
Sagar V
  • 12,158
  • 7
  • 41
  • 68
  • 1
    How does this address OP's "function in loop" issue? Also, an edit has made your answer invalid. – Kyll Mar 25 '17 at 11:07