0

I'm trying to create several links and bind an onclick handller to them inside a loop. On clicking the link, I want to display an alert box which indicates the link number (1 for 1st link, 2 for second link, 3 for second link and so on).

<html>
<body>
</body>
</html>

<script type = 'text/javascript'>
for (var i = 0; i < 10; i++) {
    var link = document.createElement("a");
    link.innerHTML = "Link " + i;
    link.href = '#';
    link.onclick = function () {
        alert("This is the link " + i);
        return false;
    };
    document.body.appendChild(link);
}
</script>

For some reason, I get the same alert message "This is the link 10" when I can click on any link.

Could it be because the parameters to the alert function get binded only when the function is called ? Because ultimately the value of i is 10 after the end of loop.

0

1 Answer 1

2

Simple answer, use closure:

link.onclick = (function(j) {
    return function(){
        alert ("This is the link " + j);
        return false;
    }
})(i);
Sign up to request clarification or add additional context in comments.

10 Comments

Or better - move anonymous function out of loop at all
Was gonna say same thing, but in examples like this i still have a hard time understanding why the closure is needed exactly. ..still correct response :)
@Robert, all the functions reference the same "global" i variable, if it change they reference the new value. you need to reference a private scope variable. hence the closure.
what actually happens when you assign a self invoking function to a variable though ? Does it execute and then the returned function is assigned to link.onclick ?
The event handler in the OP's code is already a closure. The key here is to execute a function to create a new scope. That function does not have to be a closure (even though all functions are closures in JS).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.