简体   繁体   English

换行符在javascript中不起作用

[英]newline doesn't work in javascript

When I use the new line character in java-script it is not working. 当我在Java脚本中使用换行符时,它不起作用。 I post my code below. 我在下面发布我的代码。

var i=1;
while(i<=5)
{
    document.write(i+"\n");     
    i++;
}

The outcome looks like this. 结果看起来像这样。 1 2 3 4 5 1 2 3 4 5

since you are writing into HTML Document, you should write <br> 由于您正在编写HTML文档,因此应编写<br>

var i=1;
while(i<=5){
 document.write(i+"<br/>");     
 i++;
}

Instead of "\\n" , use "<br/>" , as the code below: 代替"\\n" ,使用"<br/>" ,如下代码:

var i=1;
while(i<=5)
{
    document.write(i+"<br/>");     
    i++;
}

Here is the JSFiddle. 是JSFiddle。 When accessing it, click run to see the code. 访问它时,单击运行以查看代码。

The reason that you are not seeing the newline characters as you expected is because you are likely trying to render this in HTML. 之所以没有看到预期的换行符,是因为您可能试图用HTML呈现它。 If that is the case, "\\n" is not rendered as a newline. 在这种情况下,“ \\ n”不会呈现为换行符。 Which is why @Yuriy Galanter said to include <br/> which is . 这就是为什么@Yuriy Galanter说要包含<br/> 原因 If you were to write to the console.log then it would work as you have it written. 如果要写入console.log则它将按您编写的方式工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM