【问题标题】:IE dynamically created Iframe's onload function never calledIE 动态创建 Iframe 的 onload 函数从未被调用
【发布时间】:2023-03-18 22:17:01
【问题描述】:

我无法将任何 onload 函数附加到我动态创建的 iframe 的问题上。这仅在 IE 中发生,在 FF 中有效。这是我的代码:

var ifrm = document.createElement("IFRAME");
ifrm.setAttribute("src", "legacy-hostpage.html?rnd=" + new Date().getTime());
ifrm.style.width = "100%";
ifrm.style.height = "400px";
ifrm.name = "legacy-frame";
ifrm.id = "IFRM-" + new Date().getTime();

ifrm.onload = function() {
  alert('onload onload');
};

wrapper.appendChild(ifrm); 

我希望我可以在这个项目中使用 jQuery,但我不能......你能告诉我有什么问题吗?

【问题讨论】:

    标签: html internet-explorer iframe


    【解决方案1】:

    我认为你应该为 IE 使用 attachEvent 函数。

      function myLoad() {
          alert( "onload onload" );
      }
    
      if ( window.addEventListener ) { 
          ifrm.addEventListener( "load", myLoad, false );
      }
      else if ( window.attachEvent ) { 
          ifrm.attachEvent( "onload", myLoad );
      }
      else {
          ifrm.onload = myLoad;
      }
    
      wrapper.appendChild( ifrm ); 
    

    以上代码应该可以在所有浏览器中正常运行。

    【讨论】:

    • 如果您希望事件可靠地触发,请参阅 Remy 的回答。
    • 这对我和其他人在加载 PDF 时不起作用。另一种解决方案是将您的 iframe 放入 iframe:stackoverflow.com/questions/23412047/…
    【解决方案2】:

    您应该在设置 src 属性之前添加 onload 回调。

    【讨论】:

    • 没错。如果 IFRAME 加载速度很快(例如从缓存或其他什么),您的事件处理程序可能不会触发。
    猜你喜欢
    • 2014-06-18
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 2014-11-02
    • 1970-01-01
    • 2013-03-30
    相关资源
    最近更新 更多