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
Similar Posts:
- [How to Solve] Cannot set property ‘onclick’ of null
- Python uses decorator and reports error typeerror: ‘nonetype’ object is not callable ‘
- Error in JS function referencing public page [How to Solve]
- How to Solve Error: Cannot set property ‘onclick’ of null
- history.back();history.go(-1);Invalid solution after trigger operation
- XMLHttpRequest status=0 (All You Should Know)
- cnpm install error: Package require os(darwin) not compatible with your platform(win32) node.js
- Pdostation:: bindparam vs bindvalue of PHP extension PDO MySQL
- How to Solve Phpize Run Error: Cannot find config.m4
- SyntaxError: missing ; Problem record of before statement