创建一个iframe,然后使用jQuery向其添加数据 [英] Create an iframe then append data to it with jQuery
问题描述
我正在尝试对油脂猴子用户脚本进行一些修改,以实现所需的功能.代码就像
I am trying do some modification to an greasemonkey userscript to implement a feature I need. The code is like
showAddress:function(addrString,type)
{
this.addrBox=$('<div id="batchPublish"></div>')
.append('<div id="batchHeader"></div>')
.append('<div id="batchContent" style="float:left;clear:both"></div>');
.........
var batchContent=this.addrBox.find('#batchContent')
.append('<pre width="300" style="text-align:left" id="batchedlink"></pre>');
this.addrBox.find('#batchedlink').css({'width':'500px','height':'250px','overflow':'auto','word-wrap': 'break-word'})
.append(addrString);
$.blockUI({message:this.addrBox,css:{width:"520px",height:"300px"}}); }
基本上,此代码将数据写入html.我要实现的是将"addrString"写入嵌入式iframe.现在它在"pre"标签中.我尝试了许多方法,但仍然没有运气.iframe始终是空的.我完全是javascript的新手,不清楚是否可行.
Basically this code writes data to html. What I want to implement is to have "addrString" written to an iframe embedded. Now It's in the "pre" tag. I have tried many approaches but still no luck. Iframe was always empty. I am completely a novice in javascript and unclear whether this is possible.
谢谢您的帮助.
推荐答案
由于您要在同一域中添加iFrame,因此可以像这样操作其内容:
( 在jsBin上观看它. )
Since you are adding the iFrame in the same domain, then you can manipulate its contents like this:
(See it in action at jsBin.)
$("#batchContent").append ('<iframe id="batchedlink"></iframe>');
/*--- Compensate for a bug in IE and FF, Dynamically added iFrame needs
some time to become "DOM-able".
*/
setTimeout ( function () {
var iframeBody = $("#batchedlink").contents ().find ("body");
iframeBody.append (addrString);
},
333
);
注意:
对于Chrome用户脚本,您显然不需要计时器延迟.但是对于FF和IE 8(我仔细检查过的其他2个浏览器),动态添加的iFrame直到由于某种原因解决"之后才可以操作.这个似乎大约需要200毫秒.
NOTE:
For a Chrome userscript, you apparently don't need the timer delay. But for FF and IE 8 (the other 2 browsers I double-checked), a dynamically added iFrame is not manipulable until after it has "settled" for some reason. This seems to take about 200 mS.
静态加载的iFrame没有此延迟,请参见jsBin演示.
A statically loaded iFrame does not have this lag, see the jsBin demo.
这篇关于创建一个iframe,然后使用jQuery向其添加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!