Home >Web Front-end >JS Tutorial >How to set variable references in js and display them on the screen

How to set variable references in js and display them on the screen

下次还敢
下次还敢Original
2024-05-07 19:57:17378browse

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 set variable references in js and display them on the screen

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:

  • Use console.log()
This displays the value of the variable in the browser's console.

<code class="js">console.log(message); // 输出:Hello, world!</code>
  • Use document.write()
This will display the value of the variable in the HTML document.

<code class="js">document.write(message); // 输出:Hello, world!</code>

3. Display in HTML

When using

document.write() to output variables, you need to ensure that they are included in the HTML document , to see the output on the page.

Create a

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:

    Use different variable reference and display methods as needed.
  • Variable names should use meaningful names to improve code readability.
  • Use
  • document.write() 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does $ mean in jsNext article:What does $ mean in js