I have the following JS:
for ( var i = 1; i <= 2; i++ ) {
    $(window).load(function() {
        alert(i);
    });
}
When the page loads, it gives me an alert twice as expected. But the strange thing is the value of i is 3 on both alert. I expect the value of i is 1 on the first alert and 2 on the second alert. What causes the problem? Thank you in advance!
UPDATE #1
What if I need to place the function inside the loop because I want to use number increment as selector? Is there a solution to this problem? Here is what I mean
for ( var i = 1; i <= 2; i++ ) {
    $( '.element-' + i + ' .span' ).click( function( event ) {              
        $( '.element-' + i + ' ul' ).show( 'fast' );         
    });
}
The click function is not fired because we already know that i = 3. I want the click function get fired when .element-1 .span and .element-2 .span is clicked. Is there a workaround?
 
     
    