JavaScript: very strange behavior with the assignment of methods in a loop

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.

+3
3

, :

<a  href="#">blah</a><br>
<a  href="#">blah</a><br>
<a  href="#">foo</a><br>

<script>
    (function() {
    var anchors = document.getElementsByTagName('a');
    for ( var i = anchors.length; i--; ) {
        var link = anchors[i];
        (function(i) {
            link.onclick = function() {
                alert(i)
            }
        })(i);
    }
    })();
</script>

i , - , i.

: http://www.jibbering.com/faq/faq_notes/closures.html

+3

. , JavaScript , .

+2

for (… in …) . for:

for (var i=0; i<buttons.length; ++i) {
    actions[buttons[i]] = (function(i) {
        return function() {
            alert(i);
        };
    })(i);
}
-1

Source: https://habr.com/ru/post/1721920/


All Articles