【发布时间】:2012-08-25 08:29:33
【问题描述】:
我使用以下代码动态创建 iframe。
var iframe_jquery = $("<iframe>")
.addClass("foo")
.appendTo(container); // container is a jQuery object containing a <div> which already exists
然后,我想访问它的 contentWindow,但是它是空的:
var iframe = iframe_jquery.get(0);
if (iframe){ // iFrame exists
console.log(iframe.contentWindow); // Prints "null"
var doc = iframe.contentWindow.document; // NullpointerException
}
所以我想:“也许 iframe 还没有准备好?”所以我尝试了:
iframe_jquery.ready(function(){
var iframe = iframe_jquery.get(0);
console.log(iframe.contentWindow); // Prints "null"
var doc = iframe.contentWindow.document; // NullpointerException
});
同样的结果。
怎么了?
【问题讨论】:
-
您的代码运行良好 here。您的代码中的“容器”是什么?
-
哦,我明白了——这就是问题所在。
-
您需要确保
container已经是活动 DOM 的一部分,如果它是另一个尚未放置在文档中的动态创建的元素,您会遇到这个问题。
标签: javascript html dom iframe