2017-02-12 72 views
3

我需要在一個網頁中的DIV中一個接一個地顯示多個圖像。兩幅圖像之間應該有一段時間差距。這是我爲此嘗試的代碼。javascript asynchonously更新div

$('#abc').prepend('<img id="theImg" src="D:/Image_Store/Character/Animal/Pet/cat2.png" />') 
    wait(1000); 
    $('#abc').prepend('<img id="theImg" src="D:/Image_Store/Character/Animal/Pet/dog1.png" />') 
    wait(1000); 
    $('#abc').prepend('<img id="theImg" src="D:/Image_Store/Character/Animal/Pet/dog2.png" />') 
    wait(1000); 
    $('#abc').prepend('<img id="theImg" src="D:/Image_Store/Character/Animal/Pet/parrot1.png" />') 
    wait(1000); 

編輯

等待功能在這裏

function wait(ms){ 
     var start = new Date().getTime(); 
     var end = start; 
     while(end < start + ms) { 
     end = new Date().getTime(); 
     } 
    } 

但這不工作,只顯示最後一個圖像。我怎麼弄出來的?

+0

皮斯提供的jsfiddle – Mazz

+0

出於好奇,你從哪裏來與「等待」功能? – csm

+0

我增加了這個功能 – Nim

回答

5

您不能暫停在瀏覽器中的行之間執行JavaScript代碼。 (不是一個有用的方式; alert等等。)或者至少,如果你這樣做,瀏覽器的整個UI(或至少該選項卡)鎖定,並且不會呈現頁面更新。

相反,安排了一系列的定時回調來更新你的形象:

[ "D:/Image_Store/Character/Animal/Pet/cat2.png", 
    "D:/Image_Store/Character/Animal/Pet/dog1.png", 
    "D:/Image_Store/Character/Animal/Pet/dog2.png", 
    "D:/Image_Store/Character/Animal/Pet/parrot1.png" 
].forEach(function(img, index) { 
    setTimeout(function() { 
     $("<img>").attr("src", img).prependTo("#abc"); 
    }, 1000 * index); 
}); 

在那裏,我們安排0毫秒後的第一次更新,1000毫秒後的第二,2000毫秒後的第三等


注意:您的原始編碼是添加img元素具有相同的id值。上面的代碼仍然使用多個img元素,但不會給他們一個id,因爲在多個元素上使用相同的id是無效的。

如果你的目標是讓你有多個來源更新img元素,我們會做到這一點略有不同:

[ "D:/Image_Store/Character/Animal/Pet/cat2.png", 
    "D:/Image_Store/Character/Animal/Pet/dog1.png", 
    "D:/Image_Store/Character/Animal/Pet/dog2.png", 
    "D:/Image_Store/Character/Animal/Pet/parrot1.png" 
].forEach(function(img, index) { 
    if (index === 0) { 
     // Create and append the img 
     $("<img>").attr("id", "theImg").attr("src", img).prependTo("#abc"); 
    } else { 
     // Update it 
     setTimeout(function() { 
      $("#theImg").attr("src", img); 
     }, 1000 * index); 
    } 
});