附加内容到dymanically创建的iframe得到一个空的iframe内容、dymanically、iframe

2023-09-10 18:58:29 作者:别太自作多情

我有一个jQuery的片段如下:

I have a jQuery snippet as below:

    $.ajax({
       ....
       success: function(myContent) {
          .....
          $('<iframe id="myFrame" name="myFrame">').appendTo('body').ready(function(){
              $('#myFrame').contents().find('body').append(myContent);
          });
          .....
        });
     });

在该事件被触发的第一次,只有一个IFRAME显示为空,但如果该事件被触发的第二次,内容被附加到iframe的成功,任何明显的错误在这个片段?提前致谢。

when the event is triggered at the first time, only an empty iframe displays, but if the event is triggered at the second time, content is appended into the iframe successfully, any obvious error in this snippet? thanks in advance.

推荐答案

我相信某些浏览器需要一个短暂的延时才能识别新的iframe的DOM。使用超时应该工作:

I believe some browsers need a short delay for it to recognize the DOM of a new iframe. Using a timeout should work:

$('<iframe id="myFrame" name="myFrame">').appendTo("body").ready(function(){
    setTimeout(function(){
        $('#myFrame').contents().find('body').append(myContent);
    },50);
});