appending content into a dymanically created ifram

2020-03-05 03:37发布

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?

3条回答
乱世女痞
2楼-- · 2020-03-05 03:51

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

$("#iframe_id").contents().find("body").append("Contents to display in iframe");
查看更多
劳资没心,怎么记你
3楼-- · 2020-03-05 03:54

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);
});
查看更多
小情绪 Triste *
4楼-- · 2020-03-05 04:07

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/

查看更多
登录 后发表回答