Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Im trying to add an event listener to dynamic canvas. Instead of manually writting event listener for each canvas I used a for loop. The problem is when I click at canvas1 it returns id 3. It's suppose to be 1.

<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>

<script>

var canvas = []
var totalCanvas = 2

for(var i=1;i<=totalCanvas;i++){
    canvas[i] = document.getElementById('canvas'+i);
    canvas[i].addEventListener('mousedown', function(e) { onMouseDown(e,i) }, false);
}

function onMouseDown(e,i){
    console.log('ID'+i) //returning 3
}

</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
131 views
Welcome To Ask or Share your Answers For Others

1 Answer

The issue is because by the time you raise the mousedown event the loop has completed and i is always at the last value set in the loop.

One way to fix this would be to wrap the event handler in a closure to retain the state of the i value:

var canvas = []
var totalCanvas = 2

for (var i = 1; i <= totalCanvas; i++) {
  canvas[i] = document.getElementById('canvas' + i);
  (function(i) { 
    canvas[i].addEventListener('mousedown', function(e) {
      onMouseDown(e, i)
    }, false)
  })(i);
}

function onMouseDown(e, i) {
  console.log('ID' + i) //returning 3
}
canvas {
  width: 50px;
  height: 50px;
}

#canvas1 { background-color: #C00; }
#canvas2 { background-color: #0C0; }
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...