Skip to content Skip to sidebar Skip to footer

Javascript Binding Click Handller Inside A Loop

I'm trying to create several links and bind an onclick handller to them inside a loop. On clicking the link, I want to display an alert box which indicates the link number (1 for 1

Solution 1:

Simple answer, use closure:

link.onclick = (function(j) {
    return function(){
        alert ("This is the link " + j);
        return false;
    }
})(i);

Post a Comment for "Javascript Binding Click Handller Inside A Loop"