JavaScript document.writeln() 的换行与 textContent 替代方法
创建时间 2026-12-02
最后修改 2026-12-02
document.writeln() 向 HTML 文档流写入内容,并在末尾添加换行符 \n。普通段落通常会把它折叠为空白。编写新代码时,可用 textContent 更新指定元素,并选择能保留换行的显示方式。
write() 和 writeln() 写入的内容
document.write() 不会自动添加换行。writeln() 每次调用后都会追加一个换行。示例中的 A 和 B 紧挨着,接下来的 C 前才有换行。
document.write('A');
document.writeln('B');
document.write('C');
两种方法都会将输入解释为 HTML。根据调用环境,加载完成后的调用可能清除现有内容。动态更新页面时,请使用 DOM 方法。HTML Standard · document.writeln()
旧代码中的换行何时可见
将示例用 UTF-8 保存为 writeln-legacy.html,然后在浏览器中打开。使用默认样式时,AB 与 C 之间的换行在段落中像空格,在 <pre> 中则会另起一行。示例只在解析 HTML 时写入固定字符串。
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>比较 writeln 的换行</title>
</head>
<body>
<p>普通段落</p>
<p id="normal"><script>document.write('A');
document.writeln('B');
document.write('C');</script></p>
<pre id="preserved"><script>document.write('A');
document.writeln('B');
document.write('C');</script></pre>
</body>
</html>
普通元素也可使用 CSS white-space: pre-wrap 保留换行,并允许过长的行自动折行。对空白位置有要求的日志或代码输出可使用 <pre>。CSS Text · white-space
用 textContent 更新指定元素
用 UTF-8 将代码保存为 text-content-lines.html 并打开。显示按钮用 \n 拼接数组,并更新 <pre> 的文本。清除按钮只清空输出区域。
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>分行显示文本</title>
</head>
<body>
<button id="show" type="button">显示两行</button>
<button id="clear" type="button">清除</button>
<pre id="result" aria-live="polite"></pre>
<script>
const lines = ["第一行", "<em>第二行</em>"];
const result = document.querySelector('#result');
document.querySelector('#show').addEventListener('click', () => {
result.textContent = lines.join('\n');
});
document.querySelector('#clear').addEventListener('click', () => {
result.textContent = '';
});
</script>
</body>
</html>
textContent 会将字符串作为文本插入。示例中的 <em> 会原样显示。需要真正的元素时,可用 createElement() 创建,然后用 append() 添加。DOM Standard · Node.textContent




