JavaScript output
JavaScript does not have any printing or output functions.
JavaScript displays data
JavaScript can output data in different ways:
Use window.alert() Popup Warning box.
Use the document.write() method to write the content into the HTML document.
Use innerHTML to write to HTML elements.
Use console.log() to write to the browser's console.
Use window.alert()
You can pop up an alert box to display data:
Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php.cn</title> </head> <body> <h1>我的第一个页面</h1> <p>我的第一个段落。</p> <script> window.alert(5 + 6); </script> </body> </html>
Run Example»
Click the "Run Example" button to view the online example
Manipulate HTML elements
To access an HTML element from JavaScript, you can use the document.getElementById(id) method.
Please use the "id" attribute to identify HTML elements, and innerHTML to get or insert element content:
Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php.cn</title> </head> <body> <h1>我的第一个 Web 页面</h1> <p id="demo">我的第一个段落。</p> <script> document.getElementById("demo").innerHTML="段落已修改。"; </script> </body> </html>
Run Example»
Click the "Run Example" button to view the online example
The above JavaScript statements (in the <script> tag) can be executed in a web browser:
document.getElementById("demo") is the JavaScript code that uses the id attribute to find the HTML element .
innerHTML = "The paragraph has been modified." is used to modify the HTML content (innerHTML) of the element JavaScript code.
In this tutorial
In most cases, in this tutorial we will use the method described above to output:
The following example directly Write the <p> element with id="demo" to the HTML document output:
Write to HTML document
For testing purposes, you can write JavaScript directly in HTML In the document:
Instance
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php.cn</title> </head> <body> <h1>我的第一个 Web 页面</h1> <p>我的第一个段落。</p> <script> document.write(Date()); </script> </body> </html>
Run instance»
Click the "Run instance" button to view the online instance
## Please use document.write() to only write content to the document output. If document.write is executed after the document has finished loading, the entire HTML page will be overwritten. |
Debugging in a program is the process of testing, finding and reducing bugs (errors). |