javascript - In a loop I'm appending a tag that alerts the loop index count. Why does it always alert the last index of the loop? -


for convenience, here's interactive jsfiddle version of code. here's offending code:

for in [1, 2, 3, 4, 5, 6, 7, 8]   console.log "cell #{i} created!"   cell = $('<div class="inventory-cell"></div>').mousedown (event) ->     alert "#{i} clicked!"   $("#inventory-grid").append(cell) 

and here's html:

<div id="inventory-dialog" class="dialog">         <div id="inventory-grid"></div>     </div> 

here's how it's supposed work. generate bunch of cells in loop. if click on first 1 want alert, "1 clicked!" , when click on last, want say, "8 clicked!" reason, every 1 click on says, "8 clicked". why happening?

all of callbacks refer same i variable in body, have value of 8 time of callbacks have been called.

you need create variable local each specific callback holds value of i @ time callback created:

(function(j) {     var cell = $('<div class="inventory-cell"></div>').mousedown(function(event) {         alert("#{j} clicked!");     });      $("#inventory-grid").append(cell); })(i); 

the functionally equivalent coffeescript be:

do (i) ->   cell = $('<div class="inventory-cell"></div>').mousedown (event) ->     alert "#{i} clicked!"    $("#inventory-grid").append(cell) 

the difference do shadow i instead of creating new variable, result same.

an exact translation be:

do (j = i) ->   cell = $('<div class="inventory-cell"></div>').mousedown (event) ->     alert "#{j} clicked!"    $("#inventory-grid").append(cell) 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -