jQuery add iFrame with content

2019-01-18 11:11发布

I've such problem. I need to open iframe in fancybox (I need iframe because of I need to browse through links in opened document and stay in fancybox), but I want to put content into iframe from variable, not through src attribute (I've already got content by AJAX (I need to do some checks on content before put it to iframe, so there are no way to do it instead of AJAX query), so I do not need one more query).

Fancybox do not allow to use 'content' attribute with 'type':'iframe'. So i decided to create iframe dynamically, insert my content into it, and show iframe by fancybox as a regular block.

It's like

jQuery('<iframe id="someId"/>').appendTo('body').contents().find('body').append(content);

And than

jQuery('<iframe id="someId"/>').fancybox();

But the first part do not work. I can see the iframe that was added to page but without any content (I have full html page in variable content, but when I try to append just some text it don't work as well).

What I've done wrong? Maybe there are another way to do what I need?

Thanks for your advise!

3条回答
女痞
2楼-- · 2019-01-18 11:42

your problem will be solve after calling jquery's ready method like this

<script type="text/javascript">
$(function(){
$('<iframe id="someId"/>').appendTo('body');
$('#someId').contents().find('body').append('<b>hello sajjad</b>');
});
</script>

<iframe id="someId"></iframe>
查看更多
smile是对你的礼貌
3楼-- · 2019-01-18 11:42

Has passed time of this question, but here is another solution:

var ifrm = document.createElement("iframe");
document.body.appendChild(ifrm);
ifrm.id = "someId"; // optional id
ifrm.onload = function() {
    // optional onload behaviour
}
setTimeout(function() {
    $(ifrm).contents().find("body").html(content);
}, 1);
查看更多
【Aperson】
4楼-- · 2019-01-18 11:50

What happens if you split that line in two:

jQuery('<iframe id="someId"/>').appendTo('body');
jQuery('#someId').contents().find('body').append(content);

Then change your selector to be correct, before it was creating a new iframe, not inserting it in the DOM and the calling fancybox on it, however this should work:

jQuery('#someId').fancybox();
查看更多
登录 后发表回答