0

I am making a list of divs and want each of them alert its number, but in result all my divs alert 11.

for(var i = 1; i <= 10; i++) {
    $('#chatlist').append(
        $("<div class='chatlist_cell'>" + i + "</div>").click( function() { alert(i) } )
    )
}
simd
  • 1,779
  • 3
  • 17
  • 23

1 Answers1

2

That is because you are not preserving i by making a closure

for (var i = 1; i <= 10; i++) {
  (function(index){
    $('#chatlist').append($("<div class='chatlist_cell'>" + index + "</div>").click(function() {
        alert(index)
    }))
  })(i);
}

Another option would be to use each()

 $.each(Array(10), function(index) {
  $("<div class='chatlist_cell'>" + (index + 1) + "</div>").appendTo('body').click(function() {
    console.log(index + 1)
  });
});

$.each(Array(10), function(index) {
  $("<div class='chatlist_cell'>" + (index + 1) + "</div>").appendTo('body').click(function() {
    console.log(index + 1)
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • I would recommend avoiding making functions in loops unnecessarily. Move the builder function out of the loop. It's both clearer, and avoids creating and throwing away temporary functions. (For that matter, in this particular case, `bind` would be a clear, concise solution.) – T.J. Crowder Jun 27 '15 at 07:26
  • Thanx! So if I calling external function am I need the same closure wrapper? It works, just want to ensure if there any shorter way. This wrapping kind a verbose `for (var i = 1; i <= 10; i++) { (function(index){ $('#chatlist').append( $("
    " + index + "
    ").click(selectChat(index) ) })(i); }`
    – simd Jun 27 '15 at 07:50