开发者

Passing parameters to the event functions

开发者 https://www.devze.com 2023-01-08 21:24 出处:网络
Take a look on this simple sample: <input type="button" value="btn1" id="btn1" />

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?


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号