JavaScript Output

JS can "display" data in different ways:

(1)Writing into an alert box, using window.alert();

1 <!DOCTYPE html>
2 <html>
3 <body>
4 <h1>My first example.</h1>
5 <script>
6 window.alert(5 * 6);
7 </script>
8 </body>
9 </html>
View Code

(2)Writing into the HTML output using document.write();

1 <script>
2 document.write(5 + 8);
3 </script>
View Code

But, using document.write() after an HTML document is fully loaded, will delete all existing HTML:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button onclick="document.write(5 + 6)">Try it</button>

</body>
</html>
View Code

(3)Writing into an HTML element, using innerHTML;

 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 
 5 <h1>My First Web Page</h1>
 6 <p>My First Paragraph.</p>
 7 
 8 <p id="demo"></p>
 9 
10 <script>
11 document.getElementById("demo").innerHTML = 5 + 6;
12 </script>
13 
14 </body>
15 </html>
View Code

(4)Writing into the browser console, using console.log().

 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 
 5 <h1>My First Web Page</h1>
 6 <p>My first paragraph.</p>
 7 
 8 <p>
 9 Activate debugging in your browser (Chrome, IE, Firefox) with F12, and select "Console" in the debugger menu.
10 </p>
11 
12 <script>
13 console.log(5 + 6);
14 </script>
15 
16 </body>
17 </html>
View Code

这样就可以按F12调试自己的代码了。

原文地址:https://www.cnblogs.com/Bonnieh/p/5656454.html