JavaScript document.write 与 document.writeln 的区别

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”中右键 –> 检查,可以查看到如下源码:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值