Why the for loop in javascript doesn't work as expected -
this question has answer here:
<html> <head> <style> div{ border: 1px solid black; width: 50px; height: 50px; } </style> <script> window.onload = function(){ var divv = document.getelementsbytagname("div"); for(i=0; i<divv.length; i++){ divv[i].onclick = function(){ alert(i); } } } </script> </head> <body> <div></div> <div></div> <div></div> </body> </html>
this code. want show user index of div
clicking everytime click div, every time click different div, alert same value 3
try :
function myclickhandler(i) { alert(i); } window.onload = function(){ var divs = document.getelementsbytagname("div"); for(var = 0; < divs.length; i++) { divs[i].onclick = myclickhandler(i); }
Comments
Post a Comment