2012-02-10 20 views
3

可能重複:
Multiple ajax calls inside a each() function.. then do something once ALL of them are finished?jQuery的:每個後,執行代碼()包含負載()■完全結束

基本上,我想的每個()循環後運行的功能包含每個循環的load()完全結束。加載每個鏈接需要一些時間,並且正在等待瀏覽器趕上,但腳本已經轉移到下一步。有任何想法嗎?

jQuery('#theId a').each(function() { // contains many links 
    toLoad = jQuery(this).attr('href'); 
    jQuery('#containment').load(toLoad, function(response) { 
     //do stuff 
    }); 
}); 

//... Do stuff after the above is really complete. 
+0

使用each()的索引參數來倒數對象,並使用負載的回調條件 – ggzone 2012-02-10 17:24:58

+1

執行此操作的最佳方法是使用延遲對象。我即將發佈一個示例,但看到上面的鏈接。使用該問題的最佳答案。 – 2012-02-10 17:29:17

+0

難道你不能先給最後一個元素添加一個類('$('a:last')。addClass('lastlink');'),然後當你遍歷所有鏈接並運行load()時,如果你所在的元素擁有你之前分配的類('lastlink'),只需調用一個包含你想要從load()回調執行的所有東西的函數? – j08691 2012-02-10 17:32:36

回答

5

嘗試是這樣的:

var e = jQuery("#theId a"), l = e.length; 
e.each(function() { 
    toLoad = this.attr("href"); // I'm fairly sure "this" is already a jQuery object 
    jQuery("#containment").load(toLoad, function(response) { 
     // do stuff 
     l--; 
     if(l == 0) { 
      // this is the last one - do ending stuff here. 
     } 
    }); 
}); 

如果「這個」還不是jQuery對象,只是恢復該行你所擁有的。

+0

'this'是指DOM元素。 – 2012-02-10 17:28:35

+0

公平 - 我不使用jQuery,所以我不知道:D – 2012-02-10 17:29:22

+0

這很好用。謝謝! – 2012-02-10 20:46:43

相關問題