【问题标题】:Firefox strange behaviour when working with javascript on an iframe在 iframe 上使用 javascript 时,Firefox 出现奇怪的行为
【发布时间】:2010-07-15 12:59:31
【问题描述】:

我在 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中的简单方法。

【问题讨论】:

    标签: javascript firefox iframe behavior


    【解决方案1】:

    您需要将 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/

    【讨论】:

    • 我知道有一个简单的解释:) 谢谢这个完美的作品
    • 这不是解释,它是解决核心问题的一种变通方法,它没有完全解决。
    • 我确实尝试使用 jQuery 重写它,但仍然不得不使用超时。任何想法 - jsfiddle.net/xeGSe/2
    • 问题确实不应该这样解决,应该使用@roryf解决方案
    【解决方案2】:

    您的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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多