为什么 <br> 换行而 \n 在 JS 中失败

Why does <br> make a new line and \n fails to in JS

我正在编写一个简单的 javascript 程序,我发现当我在 document.write(""); 中使用 \n 时,它不会换行。当我使用 <br> 标签时它起作用了。

我想知道为什么 \n 无法换行而 <br> 换行。

注:我完全不熟悉Javascript...

我的 Javascript 使用 br:

<head>
    <style>
    </style>
</head>

<body>
<h1>Foo App</h1>

<script charset="utf-8">
  var input = null;

        input = prompt("Enter something: ");

        for (var i = 0; i < 10; i++) {
            document.write("Your input: " + input + "<br><br>");
        }
</script>
</body>

输出:

我的 javascript 使用 \n:

<body>
    <h1>Foo App</h1>

<script charset="utf-8">
  var input = null;

        input = prompt("Enter something: ");

        for (var i = 0; i < 10; i++) {
            document.write("Your input: " + input + "\n\n");
        }
</script>
</body>

输出:

document.write() 写入一个 HTML 的块。并在 HTML、<br> 中创建一个新行。因此,如果要在使用 document.write() 时创建一个新行,则必须使用 <BR>

Document.write 创建 HTML 标记,而不是纯文本。在 HTML 中,新行由 <br/> 元素表示。如果您正在写入浏览器控制台,则不会创建 HTML 标记,因此换行符“\n”是合适的。

正如@mrid 所说,当你使用 document.write('HTML AS STRING') 是为了将 HTML 代码写成字符串,所以当你使用 \n 时,它不是 HTML 实体,所以你可以使用 <br> html 标签来写一个新行或使用实体 html 代码作为 &NewLine; 到你的代码中。

查看 HTML entities 的官方列表以快速参考。

<!DOCTYPE html> 
<html lang="en-GB"> 
<head>
<meta charset="utf-8"> 
<style> body { white-space: pre-wrap; } 
</style> 
</head>

样式 white-space: pre-wrap 会将 '\n' 显示为换行符。这是 HTML 的工作方式,这不是 JavaScript.

的问题