JavaScript document.writeln
最后修改于 2025 年 4 月 2 日
在本文中,我们将探讨 JavaScript 中的 document.writeln 方法。此方法会将文本写入文档,并在末尾添加一个换行符。它对于简单的文档生成和测试很有用。
基本定义
document.writeln 方法将一个文本字符串写入文档流,并在末尾添加一个换行符。它类似于 document.write,但在最后添加了换行符。
此方法主要在页面加载期间或用于简单的文档生成。在页面加载后使用它会覆盖整个文档。
基本的 document.writeln
此示例演示了 document.writeln 的基本用法。
<!DOCTYPE html>
<html>
<head>
<title>Basic writeln</title>
</head>
<body>
<script>
document.writeln('Hello, World!');
document.writeln('This is a new line.');
</script>
</body>
</html>
在此基本示例中,我们使用 document.writeln 将两行文本写入文档。每次调用都会在末尾添加一个换行符。
输出将出现在文档正文中,每个字符串占一行。这展示了 writeln 的基本行为。
写入 HTML 元素
此示例展示了如何使用 document.writeln 写入 HTML 元素。
<!DOCTYPE html>
<html>
<head>
<title>Writing HTML</title>
</head>
<body>
<script>
document.writeln('<h1>Welcome</h1>');
document.writeln('<p>This is a paragraph.</p>');
document.writeln('<ul>');
document.writeln(' <li>Item 1</li>');
document.writeln(' <li>Item 2</li>');
document.writeln('</ul>');
</script>
</body>
</html>
在这里,我们使用 document.writeln 来生成 HTML 元素。每次调用都会写入一部分 HTML 标记,并用换行符分隔元素。
浏览器会解释 HTML 标记,渲染出正确的标题、段落和列表。这表明 writeln 可以用来构建文档结构。
将变量与 writeln 一起使用
此示例演示了如何将变量与 document.writeln 一起使用。
<!DOCTYPE html>
<html>
<head>
<title>Variables with writeln</title>
</head>
<body>
<script>
const userName = 'Alice';
const userAge = 30;
const currentDate = new Date().toDateString();
document.writeln(`<p>Name: ${userName}</p>`);
document.writeln(`<p>Age: ${userAge}</p>`);
document.writeln(`<p>Date: ${currentDate}</p>`);
</script>
</body>
</html>
在此示例中,我们将数据存储在变量中,并使用模板字面量将它们合并到我们的 document.writeln 调用中。
这表明如何通过将 JavaScript 变量与 HTML 标记结合来动态生成内容。输出显示了个性化信息。
条件性内容写入
此示例显示了如何将条件与 document.writeln 一起使用。
<!DOCTYPE html>
<html>
<head>
<title>Conditional Writing</title>
</head>
<body>
<script>
const isLoggedIn = true;
document.writeln('<h1>Welcome</h1>');
if (isLoggedIn) {
document.writeln('<p>You are logged in.</p>');
document.writeln('<button>Logout</button>');
} else {
document.writeln('<p>Please log in.</p>');
document.writeln('<button>Login</button>');
}
</script>
</body>
</html>
在这里,我们使用条件语句来确定要写入文档的内容。输出会根据 isLoggedIn 变量而变化。
这表明 document.writeln 可以与 JavaScript 逻辑结合使用,在页面加载期间创建动态内容。
写入表格结构
此示例演示了如何使用 document.writeln 创建表格。
<!DOCTYPE html>
<html>
<head>
<title>Table Creation</title>
</head>
<body>
<script>
document.writeln('<table border="1">');
document.writeln(' <tr>');
document.writeln(' <th>Name</th>');
document.writeln(' <th>Age</th>');
document.writeln(' </tr>');
document.writeln(' <tr>');
document.writeln(' <td>Alice</td>');
document.writeln(' <td>25</td>');
document.writeln(' </tr>');
document.writeln(' <tr>');
document.writeln(' <td>Bob</td>');
document.writeln(' <td>30</td>');
document.writeln(' </tr>');
document.writeln('</table>');
</script>
</body>
</html>
在此示例中,我们使用多个 document.writeln 调用来构建 HTML 表格。每一行都为表格结构做出贡献。
结果是一个格式正确的表格,包含标题和数据行。这表明 writeln 可用于创建复杂的 HTML 结构。
来源
在本文中,我们展示了如何在 JavaScript 中使用 document.writeln。此方法对于在页面加载期间进行简单的文档生成很有用。
作者
列出 所有 JS DOM 教程。