我有三个each循环,所有三个循环可能相互依赖,也可能不依赖,具体取决于所选的页面级过滤器。总共有3个过滤器
if(filter1 is selected) {
//runs first $.each loop and alters some of custom attr to DOM element
}
if(filter2 is selected) {
// Checks if filter1 was selected and are there any attr changes done by it
// runs second $.each loop and alters some of custom attr to DOM element
}
filter3 .... So on
问题是我需要知道filter1中的第一个循环是否已完成其任务,然后只运行第二个过滤器循环,以便我可以完美地获得filter1完成的所有attr
更改。所以我试图用户延迟对象。下面是我的代码。
var defer = $.Deferred();
if(filter1) {
$.each()
.promise
.done(function(){
defer.resolve();
return defer.promise()
});
}
// same goes for filter2 and filter3
现在我想知道是否选择了filter1 [执行循环并返回promise]或 未选择[返回 promise ],然后按照相同的流程进入第二个过滤器。我如何实现它,以及我如何知道所有 3 个循环都已完成其执行。 注意:上面的过程中根本没有ajax调用。
最佳答案
使用$.when
进行聚合和then
链接。
function handleFirstFilter(){
if(firstFilterSelected){
var ps = [];
$.each(elements, function(el){
ps.push(el.animate(...).promise()); // add all the promises
});
return $.when.apply($, ps); // aggregate over them
}
return $.Deferred().resolve(); // return an empty promise resolved, nothing to do
}
// the other two filters are similar in pattern, can extract it to a function
// now execute them all with each stage waiting for the previous.
handleFirstFilter().then(handleSecondFilter).then(handleThirdFilter)
关于javascript - 在 jQuery 中的多个 $.each 循环中使用 deferred,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29713678/