将内容附加到动态创建的 iframe 会得到一个空的 iframe动态、内容、iframe

2023-09-07 09:57:14 作者:故事与你

我有一个如下的 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?

推荐答案

我相信有些浏览器需要短暂的延迟才能识别新 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);
});