closure 2 - douglas crockford

by Alejandro M

HTML

<p class="tryme">Try Me</p>
<p class="tryme">Try Me</p>
<hr />
<p class="clickme">Click Me</p>
<p class="clickme">Click Me</p>

JavaScript

// BAD EXAMPLE
/* Make a function that assigns event handler functions to an array of nodes thewrong way.*/
/* When you click on a node, an alert box is supposed to display the  ordinal of the node.
But it always displays the number of nodes instead.*/
var add_the_handlersBad = function(nodes) {
  var i;
  for (i = 0; i < nodes.length; i += 1) {
    nodes[i].onclick = function(e) {
      alert(i);
    };
  }
};
add_the_handlersBad(document.getElementsByClassName('tryme'))
// END BAD EXAMPLE

//BETTER EXAMPLE
/* Make a function that assigns event handler functions to an array of nodes the right way.*/
/* When you click on a node, an alert box will display the ordinal of the node.*/
var add_the_handlers = function(nodes) {
  var i;
  for (i = 0; i < nodes.length; i += 1) {
    nodes[i].onclick = function(i) {
      return function(e) {
        alert(i);
      };
    }(i);
  }
};
add_the_handlers(document.getElementsByClassName('clickme'));