execute callback after jquery each iteration

我是研究僧i 提交于 2019-12-25 14:48:28

问题


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


回答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();
});



回答2:


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();



回答3:


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/



来源:https://stackoverflow.com/questions/7001388/execute-callback-after-jquery-each-iteration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!