2013-06-01 101 views
1

我希望能夠做document.write的一件事。然後延遲半秒,然後document.write更多。你知道這是可能的嗎?如果是這樣,怎麼樣?我已經試過這個到目前爲止,它沒有工作:如何document.write然後再延遲document.write

document.write("Hello!"); 
setTimeout(function(){ 
    },1000); 
document.write("hello!"); 
+1

如果可能的話,不要做'document.write',這是避之唯恐不及的技術(元素添加到正文使用jQuery,例如:'$('body')。append('

Hello!

')')。 – 2013-06-01 19:53:10

+0

@herby爲什麼不是原生的'document.body.appendChild(document.createTextNode('Hello!'))'? –

+1

@PaulS。無論通過API修改DOM。我不使用(也沒有時間和精力)學習本地API,因爲跨瀏覽器很棘手;我依賴於庫(也就是說,jQuery/zepto對我來說已經足夠了,它可以很好地實現)。 – 2013-06-01 19:57:02

回答

4

你需要把該語句裏面的setTimeout這樣。

document.write("Hello!"); 

setTimeout(function(){ 
    document.write("hello!"); 
},1000); 

第一個參數在setTimeout()是你要延遲毫秒後執行的功能。

下面是一個例子jsfiddle(不使用document.write)

+2

值得注意的是,如果頁面已經寫完, 'document.write'](https://developer.mozilla.org/en-US/docs/Web/API/document.write)調用['document.open'](https://developer.mozilla.org/ en-US/docs/Web/API/document.open),它將清除頁面。 –

+0

@PaulS。您是否在控制檯中嘗試使用防火碼? – WooCaSh

+0

@Jarek你忘了從最後一行刪除'}'。 – WooCaSh

0

您需要添加一些毫秒,以查看差異。 1000毫秒=1秒

你NEDD添加一些代碼到你的setTimeout函數,因爲這樣:

setTimeout(function(){console.log("Hello")},3000); 

的setTimeout是不是一個 「暫停」。它會在一段時間後執行自己的代碼。

請看下面的例子:http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing1

+0

你甚至看他的代碼?你說這很好?你試着解僱他的代碼嗎?我不這麼認爲。 – WooCaSh

+0

我知道。編輯我的評論,當我看到這個,但你給我一個-1之前,我發送我的更正 – gal007

+0

我認爲這是不好的-1,而編輯WooCaSh – gal007

0

你可以試試這個:

var docWriteLater = function(){ 
    document.write("Hello Later!"); 
} 

setTimeout(docWriteLater, 1000) 

document.write("hello now!"); 
+0

這將覆蓋隨後加載的頁面。 – Bergi