Tuesday 28 June 2016

javascript - Bind onclick to nodes in a loop




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?


Answer



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);

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...