23

For example, I have 10 a tags generated from an AJAX response:

<a href="#" id="b1">b1</a>
<a href="#" id="b2">b2</a>
<a href="#" id="b3">b3</a>
<a href="#" id="b4">b4</a>
<a href="#" id="b5">b5</a>
<a href="#" id="b6">b6</a>
<a href="#" id="b7">b7</a>
<a href="#" id="b8">b8</a>
<a href="#" id="b9">b9</a>
<a href="#" id="b10">b10</a>

I need to assign onclick event to each of them via loop:

for(i=1; i<11; i++) {
    document.getElementById("b"+i).onclick=function() {
        alert(i);
    }
}

This doesn't work, it only assigns onclick to the last a tag and alerts "11". How can I get this to work? I'd prefer not to use jQuery.

Caballero
  • 11,546
  • 22
  • 103
  • 163

3 Answers3

41

All of your handlers are sharing the same i variable.

You need to put each handler into a separate function that takes i as a parameter so that each one gets its own variable:

function handleElement(i) {
    document.getElementById("b"+i).onclick=function() {
        alert(i);
    };
}

for(i=1; i<11; i++) 
    handleElement(i);
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
20

A closure is what you're looking for:

for(i=1; i<11; i++) {
    (function(i) {
        document.getElementById("b"+i).onclick=function() {
            alert(i);
        };
    })(i);
}
Kevin
  • 3,771
  • 2
  • 31
  • 40
  • 2
    I'd say that Caballero has a closure where they don't want one and that they want a closure buster to force the immediate evaluation of `i`. That's what your self-executing function is doing. – mu is too short Jun 27 '11 at 00:01
  • 1
    Closure/No-Closure... I don't care! This anonymous/self-invoking solution is beautiful :) I'd have ticked this one. – Nick Apr 12 '12 at 05:36
  • Far more elegant than having a separate function. – Micah Henning Oct 19 '12 at 19:09
6

There are two ways to use closure on this problem. The idea is to create a scope with a snapshot of "i" variable for each iteration to be used by event handler.

Solution #1 (as was mentioned by Kevin):

for(i=1; i<11; i++) {
    (function(num) {

       document.getElementById("b"+num).addEventListener('click', function() {
            alert(num);
       });

    })(i);
}

Solution #2:

for (i=1; i<11; i++) {
    document.getElementById("b"+i).addEventListener('click', (function(){
        var num = i;
        return function() {
            alert(num);
        }
    })());
}
Marisev
  • 451
  • 5
  • 6