如何修复JSHint"不要在循环中创建函数" (loopfunc规则)警告?

时间:2017-03-25 10:47:26

标签: javascript jshint



	<button id="rock" class="tools">Rock</button>
	<button id="paper" class="tools">Paper</button>
	<button id="scissor" class="tools">Scissor</button>
&#13;
&#13;
&#13;

我正在尝试获取随机按钮ID名称并具有以下代码

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

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

JSHint validatorDon't make functions within a loop.http://jshint.com/docs/options/#loopfunc

请注意,我想在普通的JavaScript(没有其他框架)中解决这个问题。这里有人知道我是怎么做到的吗?

2 个答案:

答案 0 :(得分:1)

该警告试图阻止您遇到像JavaScript closure inside loops – simple practical example这样的问题(这种情况很常见,因此仅有大约1800个重复项或相关问题)。

幸运的是,您的实际代码不受此问题的影响,这意味着我们可以将该功能拉出循环。这也修复了JSHint警告:

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

答案 1 :(得分:0)

i<=buttonsCount应为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);
    }   
}