我使用 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.contentWindow
和 iframe.contentDocument
都是空的。
现在奇怪的部分来了:这只发生在其中一个 anchor 上
示例:如果我使用 URL index.html#start 直接跳转到该网站,一切正常,但在 index.html#aboutus 上我得到上述异常。
请不要问我这两个 anchor 有什么区别。它们完全不同,我不知道从哪里开始调试。
现在,我的问题是:为什么上面的代码不能在 anchor #aboutus 上运行,而是在 anchor #start 上运行?
更新:为您提供的更多信息:
我想不使用src 属性动态填充iframe 的内容,而是使用iFrameDoc.write() 函数。如您所见,您需要 iframe 文档,该文档为空。 这种方法适用于其他 anchor ,但不适用于我的一个特定 anchor “站点”。
iframeDoc.open(); iframeDoc.write('Foo'); iframeDoc.close();
我也试过等 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/