scope of variables in JavaScript callback functions

前端 未结 5 932
野的像风
野的像风 2020-12-01 06:51

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

5条回答
  •  一个人的身影
    2020-12-01 07:06

    Alternative to SLaks' answer

    $(function() {
        for (var i=0; i<2; i++) {
            $.get('http://www.google.com/', function(i) {
                return function() { alert(i); }
            }(i));
        }
    });
    

提交回复
热议问题