document.write重置一次body

时间:2010-12-22 17:32:03

标签: javascript html document

当我在加载正文后使用document.write(通过onclick事件)时,它会覆盖整个正文。我希望这是我想要实现的目标。但是,当我再次这样做时,它只是添加到以前的内容。为什么它会在第一次覆盖所有内容而只会在下一次添加?

2 个答案:

答案 0 :(得分:11)

如果文档未开放供撰写,则调用document.write会自动调用document.open

第一次调用document.write时,浏览器已加载文档,因此将其关闭以进行写入。这会调用document.open来清除现有文档并创建一个要写入的新文档。

由于浏览器未加载此内容,因此不会自动将其关闭以进行写入,因此在再次调用docment.write时会附加内容。如果您要删除内容,可以明确调用document.closedocument.open

有关详细信息,请参阅https://developer.mozilla.org/en/document.write

答案 1 :(得分:2)

使用document.write时,它会直接写入页面/正文。如果要写入某个特定元素,可以使用如下语法:

document.getElementById('elementID').innerHTML = 'your string';