JavaScript输出

JavaScript不提供任何的内建或是打印方式

JavaScript的显示方案主要有以下四种:

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

一、使用window.alert()

弹出警示框

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>JavaScript输出</title>
 6 </head>
 7 <body>
 8 <script>
 9     var str=100+11;
10 window.alert(str);
11 </script>
12 </body>
13 </html>

显示效果

二、使用 innerHTML

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

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

<!DOCTYPE html>
<html>
<body>
<h2>我的第一张网页</h2>
<p>我的第一个段落。</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

表现效果

 三、使用 document.write()

document.write() 方法仅用于测试,在页面输出

<!DOCTYPE html>
<html>
<body>
<h1>我的第一张网页</h1>
<p>我的第一个段落</p>
<script>
document.write(5 + 6);
</script>
</body>
</html> 

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

<!DOCTYPE html>
<html>
<body>
<h2>我的第一张网页</h2>
<p>我的第一个段落。</p>
<button type="button" onclick="document.write(1111111)">试一试</button>
</body>
</html>

四、使用 console.log()

使用 console.log() 方法来显示数据

可以在控制台中直接测试console.log()。F12或右击检查打开控制台。

<!DOCTYPE html>
<html>
<body>
<h1>我的第一张网页</h1>
<p>我的第一个段落</p>
<script>
console.log(111111);
</script>
</body>
</html>

显示效果

可以在控制台中直接输入

原文地址:https://www.cnblogs.com/nyw1983/p/11559876.html