JavaScript换行?

时间:2015-09-24 22:01:51

标签: javascript html css

我不知道为什么我不能在我的javascript中换行。这是代码:

document.write('It\'s ' + n + ',\n'+'SORRY, WE \'RE CLOSED');

谢谢,

2 个答案:

答案 0 :(得分:2)

该函数将输出HTML,因此通过添加<br />而非\n来创建换行符。

document.write('It\'s ' + n + ',<br />SORRY, WE \'RE CLOSED');

http://jsfiddle.net/cuLdnjhu/

但是,您不应该使用document.write() Why is document.write considered a "bad practice"?

更好的选择是document.body.innerHTMLdocument.createElement()

https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

https://developer.mozilla.org/en-US/docs/Web/API/Document

答案 1 :(得分:0)

适合我。

<span style="white-space:pre">
<script>
var n = 10;
document.write('It\'s ' + n + ',\n'+'SORRY, WE\'RE CLOSED');
</script>
</span>