我使用以下代码动态创建一个 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
});
同样的结果。
怎么了?
最佳答案
我上周在玩 iframe(构建 rtf 编辑器)时遇到了这个问题,是的,它还没有准备好。
我想如果我把它放在 .ready()
中,它会起作用,但是 .ready()
是在 DOM 准备好时,而不是在 iframe 时已经加载了它的内容,所以我最终用 jQuery .load()
包装了我的代码。
那么试试这个:
$(function () {
$("#myiframe").load(function () {
frames["myframe"].document.body.innerHTML = htmlValue;
});
});
希望对你有帮助
关于javascript - 为什么 iframe.contentWindow == null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12199797/