Create an iframe then append data to it with jQuery

痴心易碎 提交于 2021-01-28 08:50:18

问题


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"}}); }

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.

Thank you for the help.


回答1:


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
);

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.

A statically loaded iFrame does not have this lag, see the jsBin demo.




回答2:


Sort of hard to tell exactly what you're asking -- but if you want to know whether or not you can append DOM elements to an iFrame, the answer is "no".



来源:https://stackoverflow.com/questions/8394438/create-an-iframe-then-append-data-to-it-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!