2012-12-25 55 views
1

我想改變一個div的內容3次,每次更改之間延遲1秒。 delay()並不在此代碼的工作:排隊html函數

$('#import-status-msg').html('Importing content ..').delay(1000). 
html('Organizing content ..').delay(1000). 
html('Eating burrito ..'); 

我得到直接「吃捲餅」。完成這件事最簡單的方法是什麼?

回答

1

一個更通用的解決方案,使用jQuery的queue功能:

var gen = function (str, delay) { 
    return function (n) { 
    $(this).html(str); 
    setTimeout(n, delay || 1000); 
    }; 
}; 

$('#import-status-msg').queue([ 
    gen('Importing content ..'), 
    gen('Organizing content ..'), 
    gen('Eating burrito ..') 
]); 

http://jsbin.com/oraler/1/

+0

你能解釋一下setTimeout函數行裏發生了什麼嗎? – soundswaste

+0

使用隊列,回調將被調用一個* next * -function('n'參數)。這個函數或者什麼都不做(隊列結束)或者調用隊列中的下一個回調。 'setTimeout'只是延遲移動到隊列中的下一個cb。 – Yoshi

+0

謝謝,它非常全面和有教育意義! – soundswaste

2

使用的setTimeout功能:

setTimeout(function() { 
    $('#import-status-msg').html('Importing content ..'); 
    setTimeout(function() { 
     $('#import-status-msg').html('Organizing content ..'); 
     setTimeout(function() { 
      $('#import-status-msg').html('Eating burrito ..'); 
     }, 1000); 
    }, 1000); 
}, 1000); 

不能使用jQuery的延遲() - 功能只對標準效果隊列如的效果。動畫。

+0

謝謝!如果有2-3條陳述,這是一個很好的方法。 – soundswaste

0
var q = ['Importing content ..','Organizing content ..','Eating burrito ..']; 
$("#test").html(q[0]); 
var i = 1; 
var p = setInterval(function(){ 
    $("#test").html(q[i]); 
    i++; 
    if(i==q.length){ 
     clearInterval(p); 
    } 
},1000); 

fiddle