jQuery 添加带有内容的 iFrame
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4614850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery add iFrame with content
提问by krasilich
I've such a problem. I need to open iframe in fancybox (I require iframe because I need to browse through links in the 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 putting it to iframe, so there are no way to do it instead of AJAX query), so I do not need one more query).
我有这样的问题。我需要在fancybox中打开iframe(我需要iframe,因为我需要浏览打开文档中的链接并留在fancybox中),但我想将内容从变量放入iframe,而不是通过src属性(我已经有了内容通过 AJAX(在将内容放入 iframe 之前,我需要对内容进行一些检查,因此除了 AJAX 查询之外,没有办法做到这一点),因此我不需要再进行一次查询)。
Fancybox does 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.
Fancybox 不允许将 'content' 属性与 'type':'iframe' 一起使用。所以我决定动态创建 iframe,将我的内容插入其中,并通过fancybox 将 iframe 显示为常规块。
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 does 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 doesn't work as well).
但是第一部分不起作用。我可以看到添加到页面但没有任何内容的 iframe(我在可变内容中有完整的 HTML 页面,但是当我尝试仅附加一些文本时,它不起作用)。
What I've done wrong?
我做错了什么?
Maybe there is another way to do what I need?
也许有另一种方法可以做我需要的事情?
回答by sajjad hussain
your problem will be solve after calling jquery's ready method like this
像这样调用jquery的ready方法后,您的问题将得到解决
<script type="text/javascript">
$(function(){
$('<iframe id="someId"/>').appendTo('body');
$('#someId').contents().find('body').append('<b>hello sajjad</b>');
});
</script>
<iframe id="someId"></iframe>
回答by Marcus Whybrow
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:
然后在创建新的 iframe 之前将您的选择器更改为正确的,而不是将它插入到 DOM 中并在其上调用fancybox,但是这应该可以工作:
jQuery('#someId').fancybox();
回答by Igor Parra
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);