gpt4 book ai didi

javascript - document.open 和 document.close 是必要的吗?

转载 作者:可可西里 更新时间:2023-11-01 02:55:08 25 4
gpt4 key购买 nike

我正在测试一些 JavaScript 代码,并意识到这段代码......

var msg = "Hello, World!";
document.open();
document.write(msg);
document.close();

...与这个结果相同:

var msg = "Hello, World!";
document.write(msg);

有什么区别?

最佳答案

围绕 document.write 的许多行为是在正式规范之前建立的,因此行为在浏览器中是不一致的并且有些随意。但是,行为现在相当一致,但根据调用时间的不同会有所不同。

不鼓励使用document.write,但它仍然有用。它无处不在的支持意味着如果确实需要适应旧的浏览器,它可以用作其他技术的替代品。

在加载文档时

如果您在加载文档时使用 document.write(例如文档源中的脚本元素),则无需调用打开或关闭。导航到时打开文档,内容加载完成时关闭(即 load 事件发生时)。因此,只要在加载 发生之前执行所有写入语句,浏览器就会完成剩下的工作。

窗口 load 事件调度后

一旦文档完成加载(例如 load 事件已被分派(dispatch)),那么对 document.write 的调用将首先调用 clear 这将清除文档的全部 内容,所有内容。在这种情况下,并非所有浏览器都会在对 write 的调用结束时自动调用 close

一些浏览器会进行猜测并似乎在稍后调用关闭(IE?),其他浏览器(Firefox、Safari)将保持文档打开,这可能会导致一些异常行为。 p>

子窗口

如果你打开一个子窗口,例如使用 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();
}

在这种情况下,您永远不会看到 Google,调用 write 会在页面加载并写入新内容时清除页面。

此外,浏览器不会自动调用关闭,您可以对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>'
)
}

您可能会在选项卡或窗口中看到一些动画,表明它仍在加载。

如果在上面,openWindow 在结束之前调用了 document.close,那么随后对 writeToWindow 的调用将首先清除文档,因此div 是文档中的唯一元素(以及由浏览器自动添加的强​​制性 HTML、HEAD 和 BODY 元素,并且可能是通过纠错添加的 TITLE)。

因此,在这种情况下,您应该在适当的时候调用close

OP

如果在加载期间调用以下内容,则:

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();

所以只有 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>'
)
}

关于javascript - document.open 和 document.close 是必要的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27854494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com