JSLint Keeps Warning Me About Calling a Function Within A Loop
I use JSlint to check my JavaScript on a regular bases, most of the time it just for light scripts that I just need to check to make sure that I don't have a typo. But occasionally I check more robust scripts and I find myself presented with an error message that says "Problem at line XXX character XX: Be careful when making functions within a loop. Consider putting the function in a closure".
I know I've come across this in the past and I know that I fixed it, but the problem is I can never remember what the heck I did to fix it. Then I remembered that I have a blog! I can just put it there and never have to search far for the answer ever again!
Here's the problem:
function myHappyFunction() { var a = document.getElementsByTagName('a'); for(var i = 0; i <= a.length - 1; i++) { a[i].onclick = function(e) { alert('Ouch!'); }; }}