0

So basically I make a bunch of buttons with JQuery, and want to give them all some common "onclick" function, but want said function to know unique information about the button that clicked it. Using the below method, the alert message prints "This bug makes me want to beat my head against a wall 10 times", regardless of the button pressed. What the bizz, man? Thanks for your help!

function createButtons()
{
 for(var i=0; i<10;i++)
 {
  $('#Mystical_land_of_buttons').append('<button class="'+i+'">'+i+'</button>');
  $('button.'+i).click(function(){gimmeYoDigits(i);});
 }
};

function gimmeYoDigits(id)
{
 alert("This bug makes me want to beat my head against a wall "+id+" times.");
}

2 Answers2

0

You need to use closure for this:

for(var i=0; i<10;i++) {
    // ...
    (function(i) {
        $('button.'+i).click(function(){gimmeYoDigits(i);});
    })(i);
antyrat
  • 27,479
  • 9
  • 75
  • 76
0

This is because the variable i is no longer what you expect when the click function is executed. You could do the following:

var btn = $('<button>'+i+'</button>');
$('#Mystical_land_of_buttons').append(btn);
btn.data('id',i).click(function(){gimmeYoDigits($(this).data('id'));});
Justin Bicknell
  • 4,804
  • 18
  • 26