0

How can I properly execute the function f when the each iteration has finished so I can count the elements with that particular class?

This gives 0 instead of 16;

f = check_hfouten();
$.each(rest, function(idx, val,f) { 
  //alert(idx + ': ' + val); 
  $('td.info.'+idx).children('span').addClass('fout').attr('title',val).end().parent('tr').find('input').addClass('overlayed').click(function(){$(this).removeClass('overlayed')});
    $('.tag_cloud.'+idx).addClass('reminder');
}).function(f);

thanks in adv Richard

Richard
  • 4,418
  • 11
  • 58
  • 87

3 Answers3

6

each is not asynchronous so you don't need a callback. Just call it in sequence:

f = check_hfouten();

$.each(rest, function(idx, val) { 
  //alert(idx + ': ' + val); 
  $('td.info.'+idx).children('span').addClass('fout').attr('title',val).end().parent('tr').find('input').addClass('overlayed').click(function(){$(this).removeClass('overlayed')});
    $('.tag_cloud.'+idx).addClass('reminder');
});

f();
James Montagne
  • 75,784
  • 13
  • 108
  • 129
1

Place the call to f() in the body of the each() callback:

$.each(rest, function(idx, val,f) { 
    //alert(idx + ': ' + val); 
    // -Snip-
    $('.tag_cloud.'+idx).addClass('reminder');
    f();
});
George Cummins
  • 27,682
  • 8
  • 67
  • 90
  • maybe,I should do this, because if I place it outside the each, it is faster then the each. – Richard Aug 09 '11 at 19:03
  • 1
    If you place it outside the each, `f()` gets called once. If you place it within, `f()` is called for each selected element. Which do you want? – George Cummins Aug 09 '11 at 19:05
  • outside it runs faster then the each, that's the problem – Richard Aug 09 '11 at 19:07
  • So each does have a callback! I placed the call to f inside like you said and changed the code in f so it is not redundant anymore, thanks @George – Richard Aug 10 '11 at 14:37
1
group = $("p")
$.each(group, function(idx, val,f) { 
  alert(idx + ': ' + val); 
  if(idx == group.length - 1)
      alert("done");
});

The messy way :P

http://jsfiddle.net/cwDjL/

Joseph Marikle
  • 72,900
  • 16
  • 109
  • 126