Tag Archives: Don’t make functions within a loop

How to Solve JSLint Error: Don’t make functions within a loop

Recently, when writing JavaScript, I often encounter the error of don’t make functions within a loop. In fact, it doesn’t matter much. Even if an error is reported, it doesn’t affect the execution of the code. However, I just feel unhappy, very unhappy

The main problem is when there are multiple onclick events in the for loop

for(i=0;i<length;i++){
(function(i){
pics[i].onclick=function(){
alert(i);
};
}(i));
}

 

In fact, the above code has actually solved the error of don’t make functions within a loop. This error is to prevent the scope and independent variables between functions and loops. I won’t talk about the details

But hateful is, even if you use closure, he will continue to report errors, that evil little red wave

After checking a lot of things on the Internet, I finally found the solution jslint error explanation here

for(i=0;i<length;i++){
pics[i].onclick=fs(i);
}
functionfs(i){
returnfunction(){
alert(i);
};
}

In fact, the above code is that it shouldn’t be written like this. I feel that it will be very messy after writing like this, but it doesn’t report error