导航
×
   ❮   
HTML CSS JavaScript PHP Go ECMS

JavaScript 教程

JS 简介 JS 如何使用 JS 输出 JS 语法 JS 语句 JS 注释 JS 变量 JS 运算符 JS 条件语句 JS 循环 JS 字符串 JS 数字 JS 函数 JS 对象 JS 日期 JS 数组 JS 类型化数组 JS 集合 JS Map 映射 JS Math JS 正则表达式 JS 数据类型 JS 错误 JS 事件 JS 编程 JS 关键字参考 JS 保留关键字参考 JS 运算符参考 JS 运算符优先级 JS UTF-8 字符 JS UTF-8 符号 JS UTF-8 表情符号 JS 版本

JavaScript 输出


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>
亲自试一试 »

freew3c.com 中文网是独立运营的中文开发者学习平台,与 freew3c.com 无关联。提供的内容仅用于学习和测试,不保证内容的正确性。


Copyright @2020-2026 京ICP备888888号-8