You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么使用JavaScript模板字面量的代码输出没有多行渲染?

问题原因

模板字面量的换行仅属于JavaScript字符串层面的换行,当你通过document.write将字符串输出到HTML页面时,HTML的默认渲染规则会自动合并所有连续空白字符(包括换行、空格、制表符),仅展示为单个空格,因此你预期的多行效果不会呈现。

可行解决方案
  • 方案1:用<pre>标签包裹输出内容
    <pre>标签默认会保留文本内的所有空格、缩进与换行,适合需要原样展示文本格式的场景,修改后代码如下:
document.write(`<pre>Today is: ${day} 
The time now is: ${hours} : ${minutes} hrs 
The year is: ${year}</pre>`);
  • 方案2:手动插入HTML换行标签<br>
    在需要换行的位置添加<br>标签,HTML会识别该标签作为换行标记:
document.write(`Today is: ${day}<br>
The time now is: ${hours} : ${minutes} hrs<br>
The year is: ${year}`);
  • 方案3:使用innerText赋值(适配DOM操作场景)
    如果不需要使用document.write,而是将内容插入到已有DOM元素中,使用innerText属性赋值即可保留字符串内的换行:
// 假设页面存在id为content的容器元素
document.getElementById('content').innerText = `Today is: ${day} 
The time now is: ${hours} : ${minutes} hrs 
The year is: ${year}`;

补充:如果你不需要保留第二、第三行前的大量缩进,直接删掉模板字面量内对应位置的空格即可。

内容的提问来源于stack exchange,提问作者Ian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 19:36:02