2012-01-28 79 views
3

可能重複:
Continue Execution Only After .each() Completes等待。每()來完成,考慮到。每()的Ajax調用

這個問題實際上是從this discussion的延續。考慮到其回調函數中有$.get(),我們如何等待each()完成其執行?

可以找到工作實例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> 
+4

請更新喲你之前的問題,而不是隻是輕微的更新重新發布。 Alnitaks的答案是allready,包括異步請求的解決方案。 – Yoshi 2012-01-28 10:15:20

+0

等待@Yoshi,那個問題中接受的答案並不能解決如何解決這個問題。它只證實了這裏描述的事實/問題。 – moey 2012-01-28 10:20:50

+0

確定它確實如果你看看[.when]的文檔(http://api.jquery.com/jQuery.when/) – Yoshi 2012-01-28 10:22:52

回答

11

@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> = 1.8,禮貌@ jfriend00

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

現在,這是真正的解決方案!非常感謝(+1),@nikoshr。 – moey 2012-01-28 11:42:29

+0

'$ .when(def).done(postPreparation)'(即沒有_apply()_)將立即執行'postPreparation'。你知道這是爲什麼嗎?我的意思是,爲什麼在_apply()_中使用'$'作爲上下文,會讓_when()_等待? – moey 2012-12-16 16:23:55

+2

@ Siku-Siku.Com上下文無關,方法簽名是。 $ .when接受一個或多個Deferred對象或純JavaScript對象作爲其參數並調用apply時將def數組轉換爲其參數。當(def)'落入參數不是Deferred的情況下,因此立即被解決。見http://api.jquery.com/jQuery.when/ – nikoshr 2012-12-17 11:38:03