0

How can I get each click callback to show i = 1, 2, 3, 4 when clicking on each div box, respectively? jsfiddle: http://jsfiddle.net/91v7b12c/2/ The way it is now, each click shows a '4', the last value for i. Thanks.

div {
    width: 10px;
    height: 10px;
    border: 1px solid black;
}

<div id='1'></div>
<div id='2'></div>
<div id='3'></div>
<div id='4'></div>
<label></label>


var n = 4
for (var i = 0; i < n; i++) {

    $('#' + i)
    .click (function (){cb (i)})

} // end for (var i = 0; i < n; i++)

function cb (j) {
    $('label').text(j)
}
tgoneil
  • 1,522
  • 3
  • 19
  • 30
  • Let jQuery do the looping: `$('div').click(function() { cb(this.id); });` – Felix Kling Jan 29 '15 at 20:44
  • @adeneo. I'm not looking to create an array of functions, so I don't see how the link you provided answers my question. – tgoneil Jan 29 '15 at 21:07
  • @FelixKling I need a more general solution. The id coincidentally matches the variable i that I passed in. I'm not actually looking for the id of the clicked box. What if I had: var var1 = i*2 for example, and wanted the output on each clicked div to show: 2,4,6,8? – tgoneil Jan 29 '15 at 21:09
  • `$('div').forEach(function(index) { $(this).click(function() { cb(index * 2); }); });` ? – Felix Kling Jan 29 '15 at 21:14
  • *"I'm not looking to create an array of functions"* But you are creating functions inside a loop and thus have the same problem. – Felix Kling Jan 29 '15 at 21:15
  • How do I solve this without using jquery's foreach? I'm not interested in restructuring that part of the code. This is a very simple example of a larger problem I have. – tgoneil Jan 29 '15 at 21:21
  • A general solution is presented in the linked question. – Felix Kling Jan 29 '15 at 21:22
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/69850/discussion-between-tgoneil-and-felix-kling). – tgoneil Jan 29 '15 at 21:29
  • The solution is in the answer in the link, either you use `each` which will create a new scope in the callback function, or you do something like this -> **http://jsfiddle.net/91v7b12c/3/** – adeneo Jan 29 '15 at 22:21
  • Ok, thank you for providing that, but I like this solution better: .click ({i: i}, function (event){cb (event.data.i)}) event.data makes it a cleaner solution – tgoneil Jan 30 '15 at 02:42

0 Answers0