How to generate event handlers with loop in Javascript? [duplicate]

All of your handlers are sharing the same i variable.

You need to put each handler into a separate function that takes i as a parameter so that each one gets its own variable:

function handleElement(i) {
    document.getElementById("b"+i).onclick=function() {
        alert(i);
    };
}

for(i=1; i<11; i++) 
    handleElement(i);

Leave a Comment