文档对象写入方法

时间:2013-01-01 13:34:33

标签: javascript

文档对象写入方法在函数内部和外部使用时的工作方式不同。当在函数内部时,它用文件中指定的字符串替换文档上的整个元素,但是当在函数外部时,在元素下面写入内容。为什么会这样?

function foo(){document.write("Maizere")}
element.onclick=foo

当事件发生时,文档中的所有内容都将替换为write方法中指定的字符串。

1 个答案:

答案 0 :(得分:7)

当页面(确切地说,文档)已经加载时,document.write calls document.open在写入clears the current document first before writing之前。因此,将document.write放入在加载页面后调用的函数中时,将清除当前页面并使document.write中的文本取代它。

但是,当页面仍在加载时,document.write 不会调用document.open,因此无法清除页面。相反,它会立即执行并附加分配给页面上的任何内容。

相关问题