'文档'在子窗口中意外地引用了父窗口

'document' within a child window unexpectedly refers to parent

本文关键字:窗口 引用 文档 意外      更新时间:2023-09-26

我打开了一个子窗口,然后用在上面写HTML等等

childhandle.document.write(...)

效果很好。HTML包含一个ID为"foo"的输入。然后我尝试了

childhandle.document.addEventListener('DOMContentLoaded', function(event) { (document.getElementById('foo').value = 'bar'; });

这给出了一个TypeError。如果我把它改成就行了

childhandle.document.addEventListener('DOMContentLoaded', function(event) { (childhandle.document.getElementById('foo').value = 'bar'; });

似乎在版本一中,代码一定在父文档中查找元素"foo"。这似乎很奇怪——EventListener函数肯定是在子函数的作用域中运行的吗?有人能解释一下这里发生了什么吗?谢谢

匿名回调函数是在父窗口中定义的,其中定义了childhandle,其中document指的是父窗口文档,在哪里执行并不重要
请尝试使用this引用当前文档。

childhandle.document.addEventListener('DOMContentLoaded', 
    function(event) { 
        this.getElementById('foo').value = 'bar'; 
    }
);