zl程序教程

您现在的位置是:首页 >  前端

当前栏目

JavaScript document.write 与 document.writeln 的区别

JavaScript 区别 Write Document
2023-09-11 14:22:55 时间

document.write() 和 document.writeln 都是JavaScript向客户端写入的方法,writeln是以行方式输出的,但并不是指页面实际效果中的换行,两种方法在查看源代码时才看得出区别,除非是输出到pre或code(xmp也可以,但HTML4.0 已经废除xmp,使用pre或code替代)元素内 。

  • writeln 只是在字符串后面添加上“\r\n”,它并不会在网页显示的时候换行,只是输出的源代码换行而已。
  • 真正要想在显示的时候换行,请使用<br>或<br/>。
  • <pre>和<code>内的元素在显示的时候会保留源码中的空格或换行符。

看下面的例子:

<html>
    <body>
        <script>
            document.write("document.");
            document.writeln("writeln");
            document.write("can not wrap line");
            document.write("<br/>");
            document.write("only &lt;br/&gt; can wrap line");
            document.write("!");
            document.write("<br/>");
            document.write("'\\n' can not make \n new line");
            document.write("<br/>");
            document.write("<pre>one line\ntwo line</pre>")
        </script>
    </body>
</html>

运行结果如下,在“Google Chrome”中右键 –> 检查,可以查看到如下源码:

这里写图片描述