JavaScript 的四种调试输出方式

前言

       JavaScript 不提供任何内建的打印或显示函数。那么我们在日常开发的时候,需要调试输出和打印的结果的时候该怎么办法呢,这里给大家推荐4种显示方案:

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

一、使用 innerHTML

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

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

<!DOCTYPE html>
<html>
<body>

<h1>我的第一张网页</h1>

<p>我的第一个段落</p>

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

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

</body>
</html> 

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

二、使用 document.write()

向网页中写入数据:

<!DOCTYPE html>
<html>
<body>

<h1>我的第一张网页</h1>

<p>我的第一个段落</p>

<button onclick="document.write(5 + 6)">试一试</button>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h1>我的第一张网页</h1>

<p>我的第一个段落</p>

<button onclick="document.write(5 + 6)">试一试</button>

</body>
</html>

注意:在 HTML 文档完全加载后使用 document.write() 删除所有已有的 HTML ,document.write() 方法仅用于测试

三.使用 window.alert()

使用警告框来显示数据

<!DOCTYPE html>
<html>
<body>

<h1>我的第一张网页</h1>

<p>我的第一个段落</p>

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

</body>
</html> 

四 .使用 console.log() (个人推荐最方便调试的方式)

在浏览器中,您可使用 console.log() 方法来显示数据。

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

<!DOCTYPE html>
<html>
<body>

<h1>我的第一张网页</h1>

<p>我的第一个段落</p>

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

</body>
</html>

总结

以上就是今天要讲的内容,本文介绍了JavaScript 的四种调试输出方式,这里最推荐的一种方式是实用console.log ,通过 F12 来激活浏览器控制台,并在菜单中选择“控制台”,里面调试的方式。

如果这篇文章对你又把帮助的话,给博主点点关注支持一下吧~

猜你喜欢

转载自blog.csdn.net/m0_61243965/article/details/125076413
今日推荐