【问题标题】:appending content into a dymanically created iframe gets an empty iframe将内容附加到动态创建的 iframe 会得到一个空的 iframe
【发布时间】:2012-03-20 18:55:28
【问题描述】:

我有一个 jQuery sn-p 如下:

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

第一次触发该事件时,只显示一个空的 iframe,但如果第二次触发该事件,则会成功地将内容附加到 iframe 中。这个 sn-p 有什么明显的错误吗?

【问题讨论】:

    标签: jquery ajax iframe append


    【解决方案1】:

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

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

    【讨论】:

    • 依靠猜测时间延迟不是一个很好的解决方案。使用contents() 的其他答案可以毫不拖延地工作,因此更可取。
    【解决方案2】:

    我想这就是你要找的:

    $('<iframe id="myFrame" name="myFrame">').appendTo('body');
    $('iframe').contents().find('body').html(myContent);       
    

    演示:http://jsfiddle.net/vbNGA/1/

    【讨论】:

    • 您好 codefOrmer,感谢您的回答,Adam 的回答解决了我的问题。
    • @cnherald 亚当是谁?
    【解决方案3】:

    这个简单的代码可能对你有用,对我来说很好。

    $("#iframe_id").contents().find("body").append("Contents to display in iframe");
    

    【讨论】:

      猜你喜欢
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多