用于循环增量的JavaScript表现奇怪

mau*_*srx 2 javascript jquery for-loop

我有以下JS:

for ( var i = 1; i <= 2; i++ ) {
    $(window).load(function() {
        alert(i);
    });
}
Run Code Online (Sandbox Code Playgroud)

当页面加载时,它会按预期两次发出警报.但奇怪的是i两个警报的价值都是3.我希望i第一个警报的值为1,第二个警报的值为2.是什么原因造成的?先感谢您!

更新#1

如果我需要将函数放在循环中,因为我想使用数字增量作为选择器,该怎么办?有这个问题的解决方案吗?这就是我的意思

for ( var i = 1; i <= 2; i++ ) {
    $( '.element-' + i + ' .span' ).click( function( event ) {              
        $( '.element-' + i + ' ul' ).show( 'fast' );         
    });
}
Run Code Online (Sandbox Code Playgroud)

点击功能没有被触发,因为我们已经知道了i = 3.我想点击功能得到发射时.element-1 .span.element-2 .span点击的.有解决方法吗?

Sum*_*ans 5

我假设你真正想做的是for$(window).load函数内部循环,如下所示:

$(window).load(function() {
    for (var i = 0; i <= 2; i++) {
        alert(i);
    }
});
Run Code Online (Sandbox Code Playgroud)

这将在window加载后运行for循环.


说明您收到3警报的原因

3此图表说明了您当前获取警报的原因:

TIME
|     The for loop is begun (a = 0)
|     The load event on the window is handled by the specified function the load
|         function itself does not run
|     i is incremented (i++) now i = 1
|     The load event on the window is handled again
|     i is incremented (i++) now i = 2
|     The load event on the window is handled again
|     i is incremented (i++) now i = 3
|     The condition of the for loop fails so execution is discontinued
|
|     The window is loaded
|     Each of the callbacks is run and at this point i = 3 so 3 is alerted each
|         time
Run Code Online (Sandbox Code Playgroud)