I expected the code below to alert \"0\" and \"1\", but it alert \"2\" twice. I don\'t understand the reason. Don\'t know if it is a problem of jQuery. Also, please help me
An alternative solution to this is to take your callback and literally make it a named function.
Why would I want to do this?
If a function is doing something where a variable needs to take new scope then it's likely the anonymous function warrants breaking out into a new function. This will also ensure that extra complexity is not introduced to your code by having to copy variables or wrap callbacks. You're code will remain simple and self descriptive.
Example:
function getGoogleAndAlertIfSuccess(attemptNumber) {
$.get('http://www.google.com/', function() {
alert(attemptNumber);
});
}
function testGoogle() {
for (var i=0; i<2; i++) {
getGoogleAndAlertIfSuccess(i);
}
}