javascript - add event listener with argument in a loop -


this question has answer here:

i dynamically creating buttons on click event following way:

//add button for(i=1;i<=narrow+1;i++){     var btn = document.createelement("button");     btn.id="element"+i;     var t = document.createtextnode("3d view");     btn.appendchild(t);     btn.style.position="absolute";     btn.style.top="520px";     btn.style.left=100+120*(i-1)+"px"; btn.addeventlistener('click', function(){window.alert(i-1+" "+nmol[i-1]);}); 

the buttons created fine argument in function of addeventlistener event seems no increment @ all. when printed stayed value 1.

anyone can explain me why?

thanks

modify there inner closure within loop

(function(index){     btn.addeventlistener('click', function(){window.alert(index-1+" "+nmol[index-1]);});  } )(i); 

what happening i global loop , time click event fired, i last iterated value.

however, when enclose function in parenthesis, making closure reduces scope of variables within parenthesis.

see working here


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -