JS 输出

创建于 2024-12-03 / 20
字体: [默认] [大] [更大]

JavaScript 显示方案

JavaScript 能够以不同方式"显示"数据:

  • 使用 window.alert() 写入警告框
  • 使用 document.write() 写入 HTML 输出
  • 使用 innerHTML 写入 HTML 元素
  • 使用 console.log() 写入浏览器控制台

使用 innerHTML

如需访问 HTML 元素,JavaScript 可使用 document.getElementById(id) 方法。

id 属性定义 HTML 元素。innerHTML 属性定义 HTML 内容:

实例

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html> 亲自试一试 »

更改 HTML 元素的 innerHTML 属性是在 HTML 中显示数据的常用方法。


使用 document.write()

出于测试目的,使用 document.write() 比较方便:

实例

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html> 亲自试一试 »

在 HTML 文档完全加载后使用 document.write()删除所有已有的 HTML :

实例

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>
</html> 亲自试一试 »

document.write() 方法仅用于测试。



使用 window.alert()

您能够使用警告框来显示数据:

实例

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html> 亲自试一试 »

您可以跳过 window 关键字。

在 JavaScript 中,窗口对象是全局范围对象,默认情况下变量、属性和方法属于窗口对象。这也意味着 window 关键字是可选的:

实例

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
alert(5 + 6);
</script>

</body>
</html> 亲自试一试 »

使用 console.log()

出于调试目的,您可以在浏览器中调用 console.log() 方法来显示数据。

在后面的章节中,您将了解有关调试的更多信息。

实例

<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html> 亲自试一试 »

JavaScript 打印

JavaScript 没有任何打印对象或打印方法。

无法从 JavaScript 访问打印设备。

唯一的例外是您可以调用 window.print() 方法打印当前窗口的内容。

实例

<!DOCTYPE html>
<html>
<body>

<button onclick="window.print()">Print this page</button>

</body>
</html> 亲自试一试 »

0 人点赞过