使用javascript向HTMLDOM中添加文本并在其间插入换行符

使用javascript向HTMLDOM中添加文本并在其间插入换行符,javascript,Javascript,我想把这段代码的所有代码都放在单独的行上,但都放在一行上。 我已经尝试过了\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表示文档中的换行符,除非您在 要在它们

我想把这段代码的所有代码都放在单独的行上,但都放在一行上。 我已经尝试过了\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表示文档中的换行符,除非您在 要在它们之间留出空间,可以使用css样式:

<p>This is paragraph 1.</p>
<br>
<p>This is paragraph 2.</p>
在这种情况下,您不应该像这样使用标记:

p {
  display: block;
  margin-botton: 20px;
}
var p = document.createElement('p');
p.textContent = 'This is paragraph 1.';
document.body.appendChild(p);
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生成HTML。空格压缩为HTML格式,因此如果需要换行符,则需要使用元素

一般来说,不鼓励使用document.write,因为如果在文档停止编写后调用它,它将重写整个页面。通常,这些类型的更改是通过DOM节点完成的:

<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时;您需要意识到这是它正在生成的HTML,因此,您应该使用它来创建所需的结果。此外,这种方法并不是很受欢迎。

你试过吗?如果文档是XHTML。如果您正在输出HTML,顺便问一下,您需要-这将是经典的翻拍吗?请不要鼓励使用document。在类似这样的不适当情况下编写。此外,html标记本身并不确定间距。这将取决于应用于它们的css样式。
document.write('you are an explorer, entering a dragons cavern in hopes of treasure<br>be warned, the caverns are always changing<br>...');
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>you are an explorer, entering a dragons cavern in hopes of treasure
be warned, the caverns are always changing
...</pre>
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>");