0

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?

1 Answer 1

3

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

@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.
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 :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.