我正在测试一些JavaScript代码,并意识到这段代码......
var msg = "Hello, World!";
document.open();
document.write(msg);
document.close();
Run Code Online (Sandbox Code Playgroud)
...与此结果相同:
var msg = "Hello, World!";
document.write(msg);
Run Code Online (Sandbox Code Playgroud)
有什么不同?
Rob*_*obG 13
在正式规范之前建立了很多围绕document.write的行为,因此行为不一致,并且在浏览器中有些随意.但是,行为现在相当一致,但根据调用的时间而存在差异.
很大程度上不鼓励使用document.write,但它仍然有用.它无处不在的支持意味着如果需要适应旧的浏览器,它可以用作其他技术的替代品.
如果在加载文档时使用document.write(例如文档源中的脚本元素),则无需调用open或close.导航到文档时打开文档,当内容加载完成时(即加载事件发生时)关闭文档.因此,只要在加载发生之前执行所有写语句,浏览器将完成剩下的工作.
一旦文档加载完毕(例如已经调度了load事件),那么对document.write的调用将首先调用clear,这将清除文档的全部内容,一切.在这种情况下,并非所有浏览器在写入结束时都会自动调用close.
有些浏览器会猜测并且似乎稍后会调用close(IE?),其他浏览器(Firefox,Safari)会保持文档打开,这可能会导致一些异常行为.
如果你打开一个子窗口,例如使用window.open,然后从父窗口写入它,写入将在页面完成加载后发生,因此它将清除文档.例如
function openWindow() {
var win = window.open('http://www.google.com','','')
win.document.write(
'<!doctype html><title>foo</title><div>Here is a div</div>'
)
win.document.close();
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您永远不会看到Google,写入的调用会在加载并写入新内容时清除页面.
此外,浏览器不会自动调用close,您可以对document.write进行后续调用,它们将附加到现有标记,例如
// Global
var win;
// Open new window and write to it, don't close
function openWindow() {
win = window.open('http://www.google.com','','')
win.document.write(
'<!doctype html><title>foo</title><div>Here is a div</div>'
)
}
// Call some time later, content will be appended
function writeToWindow(){
win.document.write(
'<div>Here is the second div</div>'
)
}
Run Code Online (Sandbox Code Playgroud)
您可能会在选项卡或窗口上看到一些动画,表明它仍在加载.
如果在上面,openWindow在结束之前调用document.close,那么后续对writeToWindow的调用将首先清除文档,以便div是文档中唯一的元素(以及自动添加的必需HTML,HEAD和BODY元素)浏览器,可能是错误更正添加的TITLE).
因此,在这种情况下,您应该在适当的位置调用close.
如果在加载期间调用以下内容,则:
var msg = "Hello, World!";
// The following has no effect as the document is currently
// loading, therefore already open
document.open();
// Writes to the document
document.write(msg);
// The following has no effect because the window hasn't fired load yet
document.close();
Run Code Online (Sandbox Code Playgroud)
因此,在这种情况下,只有document.write行可以执行任何有用的操作.
一些播放代码:
var win;
function openWindow() {
win = window.open('http://www.google.com','','')
win.document.write(
'<!doctype html><title>foo</title><div>Here is a div</div>'
)
win.document.close();
}
function writeToWindow(){
win.document.write(
'<div>Here is the second div</div>'
)
}
Run Code Online (Sandbox Code Playgroud)