document.write()和document.writeln()有什么区别
document.write()和document.writeln()有什么区别
解决思路:
两者都是JavaScript向客户端输出的方法,对比可知写法上的差别是一个ln--line的简写,换言之,writeln 方法是以行输出的,相当于在 winte 输出后加上一个换行符。
具体步骤:
1.打开一个空白窗口。
window.open()
2.用 write 方法向空白窗口写入代码。
document.write("Line 1")
document.write("Line 2")
3.用 writeln 方法向空白窗口写入代码。
document.writeln("Line 3")
document.writeln("Line 4")
4.完整代码示例:
with(window.open()){
document.write("Line 1")
document.write("Line 2")
document.writeln("Line 3")
document.writeln("Line 4")
}
注意:两种方法仅当在查看源代码时才看得出区别。
特别提示
把上面的代码加入网页中,然后查看弹出窗口的源代码,将会看到:
Line 1Line 1Line 1
Line 2
页面效果和源代码如图所示。
页面效果:源码效果:
图 write和writeln方法的输出比较
通常情况下是这样使用的:比如有好几个页面都要用到同一个下拉选项栏,那么就可以将这一栏写成js,在每个页面进行引用:
1 document.writeln('<div class="menu">'); 2 document.writeln('<ul>'); 3 document.writeln('<li>'); 4 document.writeln('<a href="/help/cloud/index.html">云计算</a>'); 5 document.writeln('</li>'); 6 document.writeln('<li>'); 7 document.writeln('<a href="/help/api/index.html">API文档</a>'); 8 document.writeln('<ul>'); 9 document.writeln('<li>'); 10 document.writeln('<a href="/help/api/overview.html" >概述</a>'); 11 document.writeln('</li>'); 12 document.writeln('<li>'); 13 document.writeln('<a href="/help/api/signature.html" >签名认证</a>'); 14 document.writeln('</li>'); 15 document.writeln('<li>'); 16 document.writeln('<a href="/help/api/public_params.html" >公共参数</a>'); 17 document.writeln('</li>'); 18 document.writeln('<li>'); 19 document.writeln('<a href="/help/api/error_code.html">错误码</a>'); 20 document.writeln('</li>'); 21 document.writeln('<li>'); 22 document.writeln('<a href="/help/api/api_list.html">API指令列表</a>'); 23 document.writeln('</li>'); 24 document.writeln('</ul>'); 25 document.writeln('</li>'); 26 document.writeln('</ul>'); 27 document.writeln("<ul>"); 28 document.writeln('<li>'); 29 document.writeln('<a href="/help/jiaoben/index.html">智能脚本</a>'); 30 document.writeln('</li>'); 31 document.writeln('</ul>'); 32 document.writeln("<ul>"); 33 document.writeln('<li>'); 34 document.writeln('<a href="/help/beian/index.html">备案</a>'); 35 document.writeln('</li>'); 36 document.writeln('</ul>'); 37 document.writeln('<ul>'); 38 document.writeln('</div>');
特别说明
总的来说,一般情况下用两种方法输出的效果在页面上是没有区别的(除非是输出到 pre或xmp 元素内)。