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?

0

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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);
    }   
}

1 Comment

How does this address OP's "function in loop" issue? Also, an edit has made your answer invalid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.