2013-06-02 38 views
3

在這段代碼中,當編寫'FirstText'時,第一行的其餘部分被跳過。然後'SecText'寫在第2行:JavaScript換行符問題

<pre> 
<script> 
    function text(){ 
    document.write("FirstText \n SecText"); 
    } 
    text(); 
</script> 
</pre> 

但是,當我打開該功能setInterval(),話是彼此相鄰書面(線不會被忽略)。

有什麼建議嗎?

+0

你需要另一個\ n SecText後? –

+0

你需要一個
:'document.write(「FirstText
SecText」);' – Utopik

回答

8

你正在看到\n創建一個新行,因爲你在<pre />標籤內;通常您必須使用<br />才能在<pre />之外查看類似的新行。

在頁面加載完成之前調用document.write時,輸出將輸入到位;所以你會看到你的FirstText \n SecText寫在<pre />

然而,當它被稱爲後的頁面加載(內setInterval),現有的頁面被清除結果寫入之前;因此<pre />正在被刪除,並且您不再看到新的線路。

如果你還沒有在你的setInterval關閉使用document.close()document,連續調用document.write要添加到由setInterval第一迭代打開的文檔流。

您可以通過使用<br />而不是\n來解決此問題;

 <script> 
     function text(){ 
     document.write("FirstText <br /> SecText <br />"); 
     } 

     setInterval(text, 1000); 
    </script> 

欲瞭解更多信息,請參閱https://developer.mozilla.org/en-US/docs/Web/API/document.writedocument.write clears page

+0

明確解釋,謝謝我欣賞它=) – MattMoulson