JavaScript 换行问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16886366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript line break issue
提问by MattMoulson
In this snippet, when 'FirstText'is written, then rest of first line is skipped. Then 'SecText'is written on the 2nd line:
在这个片段中,当'FirstText'被写入时,第一行的其余部分被跳过。然后'SecText'写在第2行:
<pre>
<script>
function text(){
document.write("FirstText \n SecText");
}
text();
</script>
</pre>
But when I use setInterval()on this function, words are written next to each other (lines are not skipped).
但是当我setInterval()在这个函数上使用时,单词是挨着写的(不会跳过行)。
Any suggestions?
有什么建议?
回答by Matt
You're seeing \ncreate a new line because you're inside a <pre />tag; normally you have to use a <br />to see a similar new line outside of <pre />.
你看到\n创建一个新行,因为你在一个<pre />标签内;通常,您必须使用 a<br />才能在<pre />.
When you call document.writebefore the page has finished loaded, the output is entered inplace; so you'll see your FirstText \n SecTextwritten within the <pre />.
当您document.write在页面加载完成之前调用时,输出就地输入;所以你会看到你FirstText \n SecText写在<pre />.
However, when it's called afterthe page has loaded (within setInterval), the existing page is cleared beforethe result is written; hence <pre />is being removed, and you're not seeing your new line any more.
然而,当它被称为后在页面加载(内setInterval),现有的页面被清除之前的结果写入; 因此<pre />正在被删除,并且您不再看到您的新行。
As you're not closing the documentusing document.close(), successive calls to document.writein your setIntervalare adding to the document stream opened by the firstiteration of setInterval.
由于您没有关闭documentusing document.close(),对document.writein 的连续调用将setInterval添加到由 的第一次迭代打开的文档流中setInterval。
You can fix this by using a <br />rather than \n;
您可以通过使用<br />而不是\n;来解决此问题。
<script>
function text(){
document.write("FirstText <br /> SecText <br />");
}
setInterval(text, 1000);
</script>
For more info, see https://developer.mozilla.org/en-US/docs/Web/API/document.writeand document.write clears page
有关更多信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/document.write和document.write 清除页面
回答by BeNdErR
try this:
试试这个:
document.write("FirstText <br /> SecText <br/>");
working example:
工作示例:

