我正在寻找一种只在.each()完成执行后调用函数的方法.在下面的示例中,如何确保在完成后立即postPreparation()运行? $('.element').each()
$('.element').each(function() {
/**
* 'prepareLayer()' is a complex function that takes a while to complete and,
* as in this construct, needs to be invoked for each matched element. Basically,
* 'prepareLayer()' adds a lot of new HTML elements to the page.
*/
prepareLayer();
});
/**
* Ideally, this should immediately run _after_ the above function completes
* i.e. after each '.element' finishes running prepareLayer().
*
* 'postPreparation()' needs to attach some event handlers for the new HTML elements
* created in 'prepareLayer()'.
*/
postPreparation();
Run Code Online (Sandbox Code Playgroud)
从技术上讲,我正在寻找一种方法来调用回调函数.each().
注意:我刚刚在上面的例子中确认,postPreparation()只有在.each()完成后才会执行.问题是我prepareLayer()使用AJAX构建新的HTML元素,因此each()返回初步.正如@Alnitak所建议的那样,异步AJAX请求不会.each()过早地停止返回.
除非prepareLayer()正在做异步(例如AJAX或动画),否则循环中的每次传递都无法终止,直到prepareLayer()完成并且您的代码已经完成了您想要的操作.
FWIW,如果现有.each循环中没有其他操作或参数,您实际上只需要写这个:
$('.element').each(prepareLayer);
Run Code Online (Sandbox Code Playgroud)
即,不需要addtional匿名函数包装器.
另一方面,如果它正在执行异步操作,请使用延迟对象:
var def = [];
$('.element').each(function() {
// have prepareLayer return a _promise_ to return
def.push(prepareLayer());
});
function prepareLayer() {
var jqxhr = $.get(..., function() {
// do stuff with content
});
return jqxhr;
}
// use "when" to call "postPreparation" once every
// promise has been resolved
$.when.apply($, def).done(postPreparation);
Run Code Online (Sandbox Code Playgroud)