代码改变世界

js document.write 总结

2012-09-02 16:02  youxin  阅读(492)  评论(0编辑  收藏  举报

hat document.write statements must be run before the page finishes loading. This means that they must be either in the body of the page or in functions called from the body of the page. So the following is acceptable:

<script type="text/javascript">
function w1() {
document.write('hello world');
}
</script></head><body>
<script type="text/javascript">
w1();
document.write('goodbye moon');
</script>

如果我们在html 的head内使用

 document.write("<h2>hello world</h2>");

那么文本会出现在body的最开始的位置,后面才接着是原来的元素

Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page. This is almost certainly not what you intend to have happen. You should therefore avoid using document.write in situations such as this:

<script type="text/javascript">
function w1() {
document.write('hello world'); // overwrite entire page
}
window.onload = w1;
</script>

会覆盖掉原来的网页而显示hello world.

So you can only use document.write at best to write the original content of your page. It cannot be used to update the content of your page after that page has loaded.