Usage and precautions of document write()

1 Overview

The document.write() method can write HTML expressions or JavaScript code to the document.
Multiple parameters (exp1, exp2, exp3,...) can be listed, and they will be appended to the document in order, and they will not wrap by default .

We usually use the write() method in two ways: one is to use the party to output HTML in the document, and the other is to call the method outside the window. In the second case, be sure to use the close() method to close the document.

2 How to use

<html>
    <head>
    </head>
<body>
    <script type="text/javascript">
    document.write("测试文本");
    document.write("测试文本","默认不会换行");  // 多参数,默认不会换行
    document.write("<h1>测试文本</h1>")
    </script>
</body>
</html>

3 matters needing attention

The use of document.write() has two precautions that are easily overlooked and confused

  1. No line break by default
  2. After the HTML document is loaded, using document.write() to output will overwrite all the original HTML ; see the code for details
<html>
    <head>
    </head>
<body>
    <p>原本的HTML</p>
    <script type="text/javascript">
        document.write("会不会覆盖呢?")
    </script>
</body>
</html>

This will not be overwritten, it is done directly when the HTML document is loaded;

<html>
    <head>
    </head>
<body>
    <p>原本的HTML</p>
    <script type="text/javascript">
        setTimeout(() => {
     
     
            document.write("那这样会不会覆盖呢?")
        }, 1000);
    </script>
</body>
</html>

This will be overwritten, because when the HTML document is loaded, document.write() is not executed, but executed later, so the original HTML code will be overwritten

Guess you like

Origin blog.csdn.net/qq_41800366/article/details/101432518