显示方案

代码 说明
window.alert() 写入警告框
document.write() 写入 HTML 输出
innerHTML 写入 HTML 元素
onsole.log() 写入浏览器控制台

innerHTML

document.getElementById(id)

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h1>我的第一张网页</h1>
  5. <p>我的第一个段落</p>
  6. <p id="demo"></p> //定义hmtlID
  7. <script>
  8. document.getElementById("demo").innerHTML = 5 + 6; //查询id为"demo"的标签
  9. </script>
  10. </body>
  11. </html>

document.write()

主要用于测试

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h1>我的第一张网页</h1>
  5. <p>我的第一个段落</p>
  6. <script>
  7. document.write(5 + 6); //直接邮件正文显示运算结果11
  8. </script>
  9. </body>
  10. </html>

文档加载完,将删除已有的html

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h1>我的第一张网页</h1>
  5. <p>我的第一个段落</p>
  6. <button onclick="document.write(5 + 6)">试一试</button> // 点击后输出结果并删除html
  7. </body>

window.alert()

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h1>我的第一张网页</h1>
  5. <p>我的第一个段落</p>
  6. <script>
  7. window.alert(5 + 6);
  8. </script>
  9. </body>

image.png

console.log()

显示数据 请通过 F12 来激活浏览器控制台,并在菜单中选择“控制台”。

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h1>我的第一张网页</h1>
  5. <p>我的第一个段落</p>
  6. <script>
  7. console.log(5 + 6);
  8. </script>
  9. </body>
  10. </html>

image.png