等待.each()完成,给定.each()具有AJAX调用

时间:2012-01-28 10:13:33

标签: jquery asynchronous

  

可能重复:
  Continue Execution Only After .each() Completes

这个问题实际上是this discussion的延续。考虑到其回调函数中有each(),我们如何等待$.get()完成执行?

可以找到工作示例 here

/* JavaScript / jQuery. */
<script>        
function prepareLayer($n) {
    $.get('./a.html', function(data) {
        /* a.html contains: <a href="javascript:void(0);">Click me!</a> */
        $n.html(data);
    });
}

function postPreparation() {
    $('.element a').click(function() {
        alert('Ouch... you just clicked me!');
    });
}

$(function() {
    $('.element').each(function() {
        prepareLayer($(this));
    });

    postPreparation();
});
</script>

<!-- HTML -->
<div class="element"></div>
<div class="element"></div>

1 个答案:

答案 0 :(得分:12)

@Alnitak在这个问题中为您提供了大部分解决方案:Continue Execution Only After .each() Completes

var def = [];
$('.element').each(function() {
    // have prepareLayer return a _promise_ to return
    def.push(prepareLayer());
}

// use "when" to call "postPreparation" once every
// promise has been resolved
$.when.apply($, def).done(postPreparation);

缺少的部分看起来像

function prepareLayer($n) {
    var dfd=$.Deferred();
    $.get('./a.html', function(data) {
        /* a.html contains: <a href="javascript:void(0);">Click me!</a> */
        $n.html(data);
        dfd.resolve();
    });
    return dfd.promise();
}

或者使用jQuery&gt; = 1.8,@ jfriend00提供

function prepareLayer($n) {
    return $.get('./a.html').then(function(data) {
        $n.html(data);
    });
}