为什么是iframe.contentWindow == null? [英] Why is iframe.contentWindow == null?

查看:752
本文介绍了为什么是iframe.contentWindow == null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码动态创建一个iframe。

  var iframe_jquery = $(< iframe>) 
.addClass(foo)
.appendTo(container); // container是一个包含< div>的jQuery对象它已经存在

然后,我想访问其内容窗口,但它为null:

  var iframe = iframe_jquery.get(0); 
if(iframe){// iFrame exists
console.log(iframe.contentWindow); // Printsnull
var doc = iframe.contentWindow.document; // NullpointerException
}

所以我想:也许iframe还没有准备好?所以我试过:

  iframe_jquery.ready(function(){
var iframe = iframe_jquery.get(0);
console.log(iframe.contentWindow); //打印null
var doc = iframe.contentWindow.document; // NullpointerException
});

相同结果



什么问题?

解决方案

上周我遇到了这个问题,同时使用iFrames(构建rtf编辑器)是的,还没准备好



我以为如果我把它放在一个 .ready()它会工作,但 .ready()是当DOM准备好了,而不是当iFrame加载其内容时,所以我最终用jQuery .load()

所以尝试这样:

  $( function(){
$(#myiframe)。load(function(){
frames [myframe]。document.body.innerHTML = htmlValue;
});
});

希望这有帮助


I use the following code to dynamically create an iframe.

var iframe_jquery = $("<iframe>")
    .addClass("foo")
    .appendTo(container); // container is a jQuery object containing a <div> which already exists

Then, I want to access its contentWindow, but it's null:

var iframe = iframe_jquery.get(0);
if (iframe){ // iFrame exists
    console.log(iframe.contentWindow); // Prints "null"
    var doc = iframe.contentWindow.document; // NullpointerException
}

So I thought: "Maybe the iframe isn't ready yet?" So I tried:

iframe_jquery.ready(function(){
    var iframe = iframe_jquery.get(0);
    console.log(iframe.contentWindow); // Prints "null"
    var doc = iframe.contentWindow.document; // NullpointerException
});

Same result.

What's wrong?

解决方案

I had this problem last week while playing with iFrames (building an rtf editor), and yeah it's not ready yet.

I thought if I put it in a .ready() it would work, but .ready() is when the DOM is ready, not when the iFrame has loaded its contents, so I ended up wrapping my code with jQuery .load().

So try this:

$(function () {  
    $("#myiframe").load(function () {                        
        frames["myframe"].document.body.innerHTML = htmlValue;
    });
}); 

Hope this helps

这篇关于为什么是iframe.contentWindow == null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆