0
<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 is my code. I want to show the user the index of the div they are clicking everytime they click the div, but every time I click different div, it alert the same value which is 3

dramasea
  • 3,370
  • 16
  • 49
  • 77

1 Answers1

0

Try this :

function myClickHandler(i) {
    alert(i);
}

window.onload = function(){
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++) {
    divs[i].onclick = myClickHandler(i);
}
m_vdbeek
  • 3,704
  • 7
  • 46
  • 77