【问题标题】:Create an iframe then append data to it with jQuery创建一个 iframe,然后使用 jQuery 将数据附加到它
【发布时间】:2011-12-06 01:58:04
【问题描述】:

我正在尝试对greasemonkey 用户脚本进行一些修改以实现我需要的功能。代码是这样的

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 的新手,不清楚这是否可能。

感谢您的帮助。

【问题讨论】:

    标签: javascript jquery iframe userscripts


    【解决方案1】:

    由于您将 iFrame 添加到同一域中,因此您可以像这样操作其内容:
    (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 毫秒。

    静态加载的 iFrame 没有这种延迟,请参阅 jsBin 演示。

    【讨论】:

    • 我的天啊,这是我生命中的 hackyist ******* ********,但谢谢你的回答! +1
    【解决方案2】:

    有点难以准确说出您在问什么——但如果您想知道是否可以将 DOM 元素附加到 iFrame,答案是“不”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      • 2021-12-11
      • 2014-08-09
      • 2012-05-03
      • 2021-03-12
      • 1970-01-01
      • 2019-08-26
      相关资源
      最近更新 更多