Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining anonymous functions in a loop including the looping variable?

I know that this code doesn't work and I also know why. However, I do not know how to fix it:

JavaScript:

var $ = function(id) { return document.getElementById(id); };
document.addEventListener('DOMContentLoaded', function()
{
    for(var i = 1; i <= 3; i++)
    {
        $('a' + i).addEventListener('click', function()
        {
            console.log(i);
        });
    }
});

HTML:

<a href="#" id="a1">1</a>
<a href="#" id="a2">2</a>
<a href="#" id="a3">3</a>

I want it to print the number of the link you clicked, not just "4". I will prefer to avoid using the attributes of the node (id or content), but rather fix the loop.

like image 556
Tyilo Avatar asked Feb 02 '26 05:02

Tyilo


1 Answers

Wrap the loop block in its own anonymous function:

document.addEventListener('DOMContentLoaded', function()
{
        for(var i = 1; i <= 3; i++)
        {
            (function(i) {
                $('a' + i).addEventListener('click', function() {
                    console.log(i);
                })
            })(i);
        }
}

This creates a new instance of i that's local to the inner function on each invocation/iteration. Without this local copy, each function passed to addEventListener (on each iteration) closes over a reference to the same variable, whose value is equal to 4 by the time any of those callbacks execute.

like image 101
Wayne Avatar answered Feb 03 '26 18:02

Wayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!