使用jQuery的iframe [英] iframes with jQuery
问题描述
我有一个纯JS的脚本,它接受代码并将其插入iframe:
I have a script which is purely JS which takes code and inserts it into an iframe:
var html = "<p>Some <strong>HTML</strong> to insert</p>"
var iframe = document.getElementById('contentsframe');
iframe = (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument;
iframe.document.open();
iframe.document.write(html);
iframe.document.close();
我想创建一个jQuery插件,因为我经常使用这段代码,我有尝试了几种方法来获取jQuery的iframe:
I was wanting to create a jQuery plugin as I am using this bit of code a lot, I have tried a few ways to get the iframe with jQuery:
var iframe = $('#contentsframe');
var iframe = $('#contentsframe').contents();
这两个似乎都返回了调用document.open所需的错误类型的对象,写或关闭。我们知道解决方案吗?
Both of these seem to return the wrong type of object that is needed to then call document.open, write or close. does anyon know the solution to this?
干杯
Eef
推荐答案
我一直在使用你在帖子中提到的相同代码,没有问题。试试这样的事情:
I've been using the same code as you mention in your post, and have no problem. Try something like this:
var html = "<p>Some <strong>HTML</strong> to insert</p>"
var iframe = $('#contentsframe').contents().find("body").append(html);
这应该将您的代码附加到iframe正文标记的开头。
This should append your code at the start of the iframe's body tag.
编辑:在这种情况下,var iframe将设置为iframe的body元素,这可能会令人困惑。 $('#contentsframe')。contents()实际上会引用整个iframe对象。
edit: in this case the var iframe would be set to the body element of the iframe, which can be confusing. The $('#contentsframe').contents() would actually reference the entire iframe object.
这篇关于使用jQuery的iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!