簡體   English   中英

使用JavaScript將文本添加到HTML DOM並在兩者之間插入換行符

[英]Using javascript to add text text to HTML DOM and insert line breaks in between

我希望這段代碼的所有刺痛都放在單獨的行上,但是它們全部都在一行上。 我已經嘗試過\\r\\n這是前幾行:

 document.write("you are an explorer, entering a dragons cavern in hopes of treasure");
 document.write("be warned, the caverns are always changing");
 document.write("...");

\\ r和\\ n用於文檔中的換行符,與呈現的內容(html)無關,除非您位於<pre>標記內或使用css屬性whitespace來呈現文檔空白。 在html中,換行符是<br>

盡管<br>標記有時很有用,但不要無故使用它。 例如,如果您想分割兩個參數,則將具有如下標記:

<p>This is paragraph 1.</p>
<p>This is paragraph 2.</p>

要在它們之間留出空間,可以使用css樣式:

p {
  display: block;
  margin-botton: 20px;
}

在這種情況下,你應該使用的<br>是這樣的標簽:

<p>This is paragraph 1.</p>
<br>
<p>This is paragraph 2.</p>

另請注意, document.write是一種危險的做法,幾乎從來沒有必要。 除了使用document.write之外,您還可以使用javascript創建/操作如下元素:

var p = document.createElement('p');
p.textContent = 'This is paragraph 1.';
document.body.appendChild(p);

document.write生成HTML。 空格是用HTML壓縮的,因此,如果需要換行,則需要使用<br>元素。

document.write("you are an explorer, entering a dragons cavern in hopes of treasure<br>");
document.write("be warned, the caverns are always changing<br>");
document.write("...<br>");

另外,您無需將document.write字符串分成多個調用:

document.write('you are an explorer, entering a dragons cavern in hopes of treasure<br>be warned, the caverns are always changing<br>...');

一般來說,應該避免使用document.write因為如果在文檔關閉寫入后調用它,它將重寫整個頁面。 通常,這些更改是通過DOM節點完成的:

document.body.innerHTML = 'you are an explorer, entering a dragons cavern in hopes of treasure<br>be warned, the caverns are always changing<br>...';

另外,如果您需要保證文本的格式,則可以使用<pre>元素(或帶white-space: pre CSS white-space: pre )。 預格式化的文本允許使用換行符和多個空格:

<pre>you are an explorer, entering a dragons cavern in hopes of treasure
be warned, the caverns are always changing
...</pre>

如果必須使用document進行操作,請使用document.writeln而不是document.write

您需要使用HTML標簽:

document.write("<p>you are an explorer, entering a dragons cavern in hopes of treasure</p>");
document.write("<p>be warned, the caverns are always changing</p>");
document.write("<p>...</p>");

使用document.write(); 您需要意識到這是它正在生成的HTML,因此,您應該使用<br>創建所需的結果。 此外,這種方法並不是很受青睞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM