JavaScript: Very strange behavior with assigning methods in a loop

Posted by Andrey on Stack Overflow See other posts from Stack Overflow or by Andrey
Published on 2009-11-04T19:36:52Z Indexed on 2010/05/12 20:24 UTC
Read the original article Hit count: 230

Consider this code below:

<a href="javascript:void(-1)" id="a1">a1</a>
<a href="javascript:void(-1)" id="a2">a2</a>

<script type="text/javascript">
    var buttons = []
    buttons.push("a1")
    buttons.push("a2")
    var actions = []
    for (var i in buttons)
    {
    	actions[buttons[i]] = function() { alert(i) }
    }

    var elements = document.getElementsByTagName("a")
    for (var k = 0; k < elements.length; k++)
    {
    	elements[k].onclick = actions[elements[k].id]
    }

</script>

Basically, it shows two anchors, a1 and a2, and I expect to see "1" and "2" popping up in an alert when clicking on corresponding anchor. It doesn't happen, I get "2" when clicking on either. After spending an hour meditating on the code, I decided that it probably happens because dynamic onclick methods for both anchors keep the last value of "i". So I change that loop to

for (var i in buttons)
{
    var local_i = i.toString()
    actions[buttons[i]] = function() { alert(local_i) }
}

hoping that each dynamic function will get its own copy of "i" with immediate value. But after this change I get "1" popping up when I click on either link.

What am I doing wrong? It's a huge show stopper for me.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about javascript-events