Home >Web Front-end >JS Tutorial >How to set variable references in js and display them on the screen
In JavaScript, variables can be referenced and output to the screen through the following steps: 1. Declare the variable and assign a value; 2. Use console.log() to output the variable value in the console; 3. Use document.write( ) displays variable values in HTML and includes them in HTML, using the innerHTML attribute to assign variable values to HTML elements.
How to reference a variable in JS and display it on the screen
In JavaScript, reference a variable and Displaying it on the screen can be achieved by the following steps:
1. Declare variables
First, use var
, let# The ## or
const keyword declares a variable and assigns a value to it.
<code class="js">let message = "Hello, world!";</code>
2. Select display method
There are two main methods for displaying variables on the screen:
<code class="js">console.log(message); // 输出:Hello, world!</code>
<code class="js">document.write(message); // 输出:Hello, world!</code>
3. Display in HTML
When usingdocument.write() to output variables, you need to ensure that they are included in the HTML document , to see the output on the page.
tag in HTML and assign the value of the variable to it using the
innerHTML attribute.
<code class="html"><p id="message"></p> <script> document.getElementById("message").innerHTML = message; </script></code>This will cause a
tag with the message "Hello, world!" to be displayed on the page.
Tip:
with caution as it may overwrite existing HTML content.
The above is the detailed content of How to set variable references in js and display them on the screen. For more information, please follow other related articles on the PHP Chinese website!