4

I have a function add_the_handler that binds an onclick event to each node. The following example prints "3" in every alert window, when I click on any node:

var add_the_handlers = function (nodes) {

var i;
    for (i=0; i< nodes.length; i+=1) {

        nodes[i].onclick = function (e) {
            alert(i);    
        };
    }
};

fiddle is here: http://jsfiddle.net/D886E/3/

Why doesn´t the nodes print the different values 1,2,3 in the alert windows?

Simon
  • 3,563
  • 1
  • 41
  • 75

1 Answers1

5

Check this fiddle. Basically you need a function clojure to handle the attaching of the listeners to the appropriate index in the loop

var add_the_handlers = function (nodes) {

    var i;

    for (i = 0; i < nodes.length; i += 1) {
        (function (i) {
            nodes[i].onclick = function (e) {
                alert(i);
            };

        })(i);
    }
};

pnodes = document.getElementsByClassName("node");

add_the_handlers(pnodes);
karthikr
  • 92,866
  • 25
  • 190
  • 186