0

Here is the HTML

<body>
 <div>
   <button>
     Button 1
   </button>

   <button>
    Button 2
   </button>

   <button>
    Button 3
   </button>
 </div>
</body>    (script tag is in right place just left it out here)

Here is my code

(function () {

var button= document.getElementsByTagName("button");    

for (var i= 0, len= button.length; i < len ;i = i + 1) {

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

}
}()) 

So when I click on each button why are all 3 bringing back a value of 3??? Shouldn't each button bring back a different value??????

mkoryak
  • 57,086
  • 61
  • 201
  • 257

3 Answers3

3

When you are looping through the collection of buttons, you are assigning each button a function to execute when clicked. This function gives and alert displaying the value of i. When the loop completes, the value of i is set to 3, and that is what you see. If you want each button to display its own ordinal, you can set an attribute inside the loop:

button[i].setAttribute("ordinal",i);

and use the alert reading this attribute:

button[i].onclick = function(){
    alert(this.getAttribute("ordinal"));
}
Boluc Papuccuoglu
  • 2,318
  • 1
  • 14
  • 24
0

You need to isolate the scope (via a closure) in order to get this to work properly. My example below crates an immediate function that executes and returns a new function that captures the loop variable.

(function() {

  var buttons = document.getElementsByTagName("button");

  for(var i = 0; i < buttons.length; i++)
  {    
    buttons[i].onclick=(function(){      
      var n = i;
      return function(){
        alert(n);
      };
    })();
  }

})();
Mike Cheel
  • 12,626
  • 10
  • 72
  • 101
0

Try:

(function () {

var button= document.getElementsByTagName("button");

for (var i= 0, len= button.length; i < len ;i = i + 1) {
    button[i].current_i = i;
    button[i].onclick = function () {
        alert(this.current_i);
    };
} 

})()

By setting the current value of "i" to an object variable of the button, you can save it's state. This has to do with Javascript's function scope instead of object scope.

Cheers!

M1Reeder
  • 692
  • 2
  • 7
  • 22