scope of variables in JavaScript callback functions

Posted by Ethan on Stack Overflow See other posts from Stack Overflow or by Ethan
Published on 2010-05-17T23:18:18Z Indexed on 2010/05/17 23:20 UTC
Read the original article Hit count: 245

Filed under:
|

I expected the code below to alert "0" and "1", but it alert "2" twice. I don't the reason. Don't know if it is a problem of jQuery. Also, please help me to edit title and tags of this post if they are inaccurate.

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
                for (var i=0; i<2; i++) {
                    $.get('http://www.google.com/', function() {
                        alert(i);
                    });
                }
            });
        </script>
    </head>
    <body>
    </body>
</html>

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery