execute callback after jquery each iteration

2019-08-25 20:20发布

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

3条回答
家丑人穷心不美
2楼-- · 2019-08-25 20:41
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/

查看更多
神经病院院长
3楼-- · 2019-08-25 20:43

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();
});
查看更多
Animai°情兽
4楼-- · 2019-08-25 20:49

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();
查看更多
登录 后发表回答