JavaScript 空指针异常 : Why is contentWindow and contentDocument of my dynamically created iFrame always null?

标签 javascript html iframe

我使用 jQueryMobile 创建了一个单页网站。

“一页”是指整个网站仅由一个 index.html 文件组成,而不同的内容通过 anchor 显示,例如

  • index.html#start
  • index.html#contact
  • index.html#aboutus
  • 等等...

我通过 JavaScript 创建了一个 iFrame,如下所示:

var iframe = $("<iframe>").addClass("myframe").appendTo(container).get(0);
var iframeDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;

在第 2 行我得到一个异常,它指出:

Uncaught TypeError: Cannot read property 'document' of null

这似乎来自这个电话:

iframe.contentWindow.document

很明显,iframe.contentWindowiframe.contentDocument 都是空的。

现在奇怪的部分来了:这只发生在其中一个 anchor 上

示例:如果我使用 URL index.html#start 直接跳转到该网站,一切正常,但在 index.html#aboutus 上我得到上述异常。

请不要问我这两个 anchor 有什么区别。它们完全不同,我不知道从哪里开始调试。

现在,我的问题是:为什么上面的代码不能在 anchor #aboutus 上运行,而是在 anchor #start 上运行?


更新:为您提供的更多信息:

  1. 我想使用src 属性动态填充iframe 的内容,而是使用iFrameDoc.write() 函数。如您所见,您需要 iframe 文档,该文档为空。 这种方法适用于其他 anchor ,但不适用于我的一个特定 anchor “站点”。

    iframeDoc.open(); iframeDoc.write('Foo'); iframeDoc.close();

  2. 我也试过等 iframe 加载完毕。

还是一样的结果

var iframe = $("<iframe>").addClass("myframe").appendTo(container).get(0);
setTimeout(function(){
var iframeDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
}, 3000);

“加载”事件甚至没有被触发,因为还没有内容写入 iframe。

最佳答案

终于找到问题的根源了。存储在变量“容器”中的元素未正确附加到 DOM 树。这就是为什么 iframe 也不是 dom 的一部分并且没有创建文档的原因。

关于JavaScript 空指针异常 : Why is contentWindow and contentDocument of my dynamically created iFrame always null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14589550/

相关文章:

html - @font-face 变体被用作默认

javascript - 进度条达到 100% 时未提交表单

javascript - 如何在运行时在 MVC 循环中动态创建 IFrame

javascript - 如果 iframe 元素本身可见或不可见,iframe "see"内的页面是否可以跨域?

javascript - 如何在用户定义的行中创建行

javascript - 调整屏幕大小时,我的多元素轮播正在折叠(Bootstrap)

javascript - 从浏览器外部调用 Javascript 函数?

javascript - 当应用于 Javascript 中的字典时,Stringify 的行为很奇怪

javascript - 如何在不使用 AJAX 或 "Mega Strings"的情况下将大量 HTML 插入 DOM

html - 用 Iframe(jsfiddle) 填充空白