Consider the following code:
<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” appearing in the warning when I click on the corresponding anchor. This does not happen, I get "2" when pressed. After spending an hour thinking about the code, I decided that this was probably because the dynamic onclick methods for both anchors retained the last value of "i". Therefore, I change this 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 receive its own copy of "i" with an immediate value. But after this change, I get the message "1" when I click on any link.
What am I doing wrong? This is a great show stopper for me.