Javascript parent.document.getElementById("...") 为 null 或不是 IE7 中的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7839423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
parent.document.getElementById("...") is null or not an object in IE7
提问by sharcupine
I have done some research, but as a JavaScript novice, I can't seem to get anything to work for my specific case:
我做了一些研究,但作为一个 JavaScript 新手,我似乎无法为我的特定情况做任何事情:
I have an iframe in a page, and in that iframe's document, I have the following code:
我在页面中有一个 iframe,在该 iframe 的文档中,我有以下代码:
function fun(){
var slideTitle = api.getField('title');
parent.document.getElementById("slidecaptionOoH").innerHTML = slideTitle;
In the parent document I have:
<h4 id="slidecaptionOoH"></h4>
在父文档中,我有:
<h4 id="slidecaptionOoH"></h4>
I've tried putting a comment in between the tags, but I still get the error in IE7. The page displays fine, but obviously I don't want people to see the error.
我试过在标签之间添加注释,但在 IE7 中仍然出现错误。该页面显示正常,但显然我不希望人们看到错误。
Well, I think I've narrowed down the problem a bit. I think it may have to do with the iframe document's function executing before the parent is finished loading. I'm using the treesaver.js framework in the parent, which involves heavy DOM manipulation. When I turn off treesaver, I no longer receive the error.
嗯,我想我已经把问题缩小了一点。我认为这可能与在父级完成加载之前执行的 iframe 文档的功能有关。我在父级中使用了 treeaver.js 框架,这涉及到大量的 DOM 操作。当我关闭 treeaver 时,我不再收到错误消息。
So I guess my question now is, how do I delay the function until the parent is finished loading? Or delay the loading of the iframe document altogether?
所以我想我现在的问题是,如何延迟函数直到父级加载完成?或者完全延迟加载 iframe 文档?
回答by Prusse
You can keep pooling the parent until it has loaded the respective child with:
您可以继续合并父级,直到它加载了相应的子级:
function fun(){
var slideTitle = api.getField('title');
var el = parent.document.getElementById("slidecaptionOoH");
if (el){
el.innerHTML = slideTitle;
} else{
setTimeout(fun, 50);
}
el = null;
}
But this is just a(dirt) work around.
但这只是一个(肮脏的)解决方法。