closure loop issue

by bhupendra negi

HTML

<div id = "issue"></div>
<div id = "fix"> </div>

CSS

a{
    display:block
}

#issue{
 float:left;
 color:red;  
 cursor:pointer   
}

#fix{
    float:right;
    right:150px;
    position:relative;
    color:green;
    cursor:pointer
        
}

JavaScript

// famoue loop problem when adding events in a loop
function loadlinks()
{
   var div1 = document.getElementById("issue"); 
 for(i=0;i<5;i++)
 {
     var link = document.createElement("a");
     link.innerHTML = "LINK - "+i;
     link.onclick = function() {alert(i);}
     div1.appendChild(link);
 }
    
}

loadlinks()


// fixed closure loop issue
loadlinks2();

// Create the fragment for better performance
function loadlinks2()
{
    var div2 = document.getElementById("fix");
    var frag = document.createDocumentFragment();
    
 for(j=0;j<5;j++)
 {
     var link = document.createElement("a");
     link.innerHTML = "LINK - "+j;
     link.onclick = function(j) {
     return function() {alert(j);}
          }(j)
     frag.appendChild(link);
 }
    div2.appendChild(frag);
    
}