3

我用这个简单的脚本在 Firefox 中遇到了一个奇怪的行为:

    <html>
      <head>
        <script type="text/javascript">
            window.setTimeout(function(){
                var ifr=document.createElement("iframe");
                ifr.src="about:blank";
                document.body.appendChild(ifr);
                var doc=ifr.contentDocument || ifr.contentWindow.document,
                    div=doc.createElement("div");
                div.innerHTML="test";
                window.setTimeout(function(){
                    doc.body.appendChild(div);
                },500);
            },500);
        </script>
    </head>
  </html>

这段代码创建了一个空白 iframe 并将其附加到当前页面的正文中,然后它创建了一个包含简单文本的 div 元素并将其附加到 iframe 的正文中。

在每个浏览器(IE、Safari、Chrome、Opera)中它都可以工作,但在 Firefox(我使用的是 3.6.3 版)中,div 不会出现在 iframe 中,也不会引发错误。

我认为某处一定有一些愚蠢的错误,但我找不到它,你有什么想法吗?

PS:这些window.setTimeout只是确保 dom 加载到页面和 iframe 中的简单方法。

4

2 回答 2

5

您需要在超时中包装 iframe 文档的检索。

        window.setTimeout(function(){
            var doc=ifr.contentWindow.document || ifr.contentDocument;
            var div=doc.createElement("div");
            div.innerHTML="test";
            doc.body.appendChild(div);
        },500);

http://jsfiddle.net/xeGSe/1/

于 2010-07-15T13:08:51.220 回答
4

看起来你的setTimeout电话没有捕捉到时间问题。您最好使用onload事件来确保元素真正可用(DOMReady在 IE 中会更好但不那么容易)。尝试这个:

document.body.onload = function() {
    var iframe = document.createElement("iframe");
    iframe.src = "about:blank";
    iframe.onload = function() {
        var doc = iframe.contentDocument || iframe.contentWindow.document,
            div = doc.createElement("div");
        div.innerHTML="test";
        doc.body.appendChild(div);
    }
    document.body.appendChild(iframe);
}
于 2010-07-15T13:12:49.687 回答