views:

34

answers:

1

Take a look on this simple sample

<input type="button" value="btn1" id="btn1" />
<input type="button" value="btn2" id="btn2" />
<input type="button" value="btn3" id="btn3" />
<input type="button" value="btn4" id="btn4" />
<input type="button" value="btn5" id="btn5" />

<script>
    for (i=1; i<5; ++i){
        var btn = document.getElementById('btn' + i);
        btn.onmouseover = function(){
            alert(i);
        }
    }
</script>

I expect it should alerts for example 1 when I move my mouse on btn1, but unfortunately it alerts 5 at all!

How I can pass variables from the loop to the function?

+3  A: 

This is the closure loop issue. All the mouseovers close over the same variable, since JavaScript only has function scope. You can fix it by creating a new function, and thus a new scope.

for (i=1; i<5; ++i){
    (function(i)
    {
        var btn = document.getElementById('btn' + i);
        btn.onmouseover = function(){
            alert(i);
        }
    })(i);
}
Matthew Flaschen
God bless you! thanks :-)
Ehsan
@Ehsan Note that the formal parameter `i` and the `i` within the function body are different from the `i` initialized in the `for` statement and passed into the function as an actual parameter.
Justin Johnson
I know, thanks.In the last 10 years, it's a question in my mind, but I has no answer for it till now! Anytime I hit this wall, I solve it in a nasty way.Have a good day :-)
Ehsan