JavaScript显示数据的四种方式
1.警告框:使用window.alert()弹出警告框
<html>
<body>
<p>我的第一个段落。</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
2.写到HTML文档:使用ducument,write()把内容写到文档中
<html>
<body>
<h1>我的第一个 Web 页面</h1>
<p>我的第一个段落。</p>
<script>
document.write(Date());
</script>
</body>
</html>
结果:第一行显示<h1>的内容,第二行<p>标签的内容,第三行是时间
注意:如果在文档已完成加载后执行 document.write,整个 HTML 页面将被覆盖
<html>
<body>
<h1>我的第一个 Web 页面</h1>
<p>我的第一个段落。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction() {
document.write(Date());
}
</script>
</body>
</html>
结果:点击按钮"点我"后,页面只显示时间
3.操作 HTML 元素:使用 innerHTML 写入到 HTML 元素,document.getElementById(id) . innerHTML=”内容”
<html>
<body>
<h1>我的第一个 Web 页面</h1>
<p id="demo">我的第一个段落</p>
<script>
document.getElementById("demo").innerHTML = "段落已修改。";
</script>
</body>
</html>
结果:<p>标签中的内容会被script重新编译的内容覆盖
4.写到控制台:使用 console.log() 写入到浏览器的控制台,console.log(内容);
<html>
<body>
<h1>我的第一个 Web 页面</h1>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>