appending content into a dymanically created iframe gets an empty iframe

半城伤御伤魂 提交于 2019-12-09 01:06:12

问题


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);
    });
    .....
  });
}); 

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?


回答1:


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



回答2:


I think this is what you are looking for:

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

Demo: http://jsfiddle.net/vbNGA/1/




回答3:


This simple code may be use for you, it works fine for me.

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


来源:https://stackoverflow.com/questions/9530455/appending-content-into-a-dymanically-created-iframe-gets-an-empty-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!