0

I want to create a set of buttons, each responding with a different message to an 'onclick' event. It would be easiest to create them in a loop - unfortunately, I'm not sure how to pass the unique data to the function object when I create them. The functions I'm creating below all print "Hello, I'm 6!". What's the right way to do this in Javascript?

function makeButtonTest(rootEle)
{
    for (var i = 1; i <= 5; ++i)
    {
        var d = document.createElement("div");
        rootEle.appendChild(d);
        d.onclick = function(){ 
            alert("Hello, I'm " + i + "!");
        };
        d.appendChild(document.createTextNode("Number " + i));
    }
}
kitfox
  • 4,534
  • 3
  • 17
  • 24
  • @RokoC.Buljan: Why did you reopen it? – Bergi May 06 '15 at 22:34
  • 1
    @Bergi cause I've found later a better duplicate that might be easier for OP to understand: http://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue (cannot close again once I reopen) so I was willing to leave a comment like "Please close it again" realizing that you've already done it. Thx – Roko C. Buljan May 06 '15 at 22:37
  • 1
    @RokoC.Buljan: Ah, you're right, that's a better dupe. Only you were too late with your comment :-) – Bergi May 06 '15 at 22:40
  • @Bergi yes, sadly I realized the mistake I'm doing when it was too late. Soon after had to pick the phone... long story short, would be good to suggest on [meta] to eventually allow a link-to-dupe modification... – Roko C. Buljan May 06 '15 at 22:51

0 Answers0