2015-06-21 57 views
0

我製作了一個計時器,顯示我的新創建窗口。在新創建的窗口中創建一個div

但是,它每次重複文字,因爲我寫了一個新的行。

我想在窗口中創建div元素,所以我可以每秒更換(更新)文本。

對象:

venster = window.open('new.html','titel','width=500, height= 500'); 

我的定時器:

function stopwatch(sec){ 
    //timer 
    venster.document.write("window closes in: " + sec); 
    if(sec < 1){ 
     clearTimeout(timer); 
     venster.document.write("<h1>i will close!</h1>"); 
     //setTimeout(venster.close(),2000); 
     } 
    sec--; 
    var timer = setTimeout('stopwatch('+sec+')',1000); 
    } 

我想要的文字「窗口將關閉。」只顯示一次,而不是每一個第二本書的一個新的生產線。

+0

''是無效的HTML。 – Xufox

回答

2

您錯過了else子句。如果您想要替換整個內容,那麼innerHTML就是您要做的。 document.write將永遠只是添加。

function stopwatch(sec){ 
    if(sec < 1){ 
     venster.document.body.innerHTML = "<h1>i will close!</h1>"; // Also this h1 wasn't closed 
     setTimeout(venster.close ,1000); // And this was executed immediately rather than passing on a function 
    } else { 
     venster.document.body.innerHTML = "window closes in: " + sec; 
     setTimeout(function() { stopwatch(sec-1) }, 1000); // And this would look prettier wrapped in an anonymous function 
    } 
} 
+0

我仍然一遍又一遍地看到相同的文字,直到我的計時器打開爲止0 – Thibaut

+0

嗯嗯,我讀錯了。我認爲問題出在'h1'而不是'窗口在文本中關閉'。 'document.write'會一直添加,不能代替 – Jan

+0

是的,我希望它替換它。 – Thibaut

0

問題是變量timer只存在於函數作用域中。當你想清除計時器時,它沒有任何價值。

定義變量timer以外的函數。