【问题标题】:Set iframe innerHTML without loading page in it (with jquery)设置 iframe innerHTML 而不在其中加载页面(使用 jquery)
【发布时间】:2011-11-22 11:51:14
【问题描述】:

我想动态设置 iframe 的内容,但之前 iframe 中没有加载任何页面。

我正在这样做:

iframe = $('<iframe id="thepage"></iframe>');

iframeHtml = 'iframeHtml';
$('body').append(iframe);

iframe
.contents()
.html(iframeHtml);

但它不起作用,html仍然是空的。

【问题讨论】:

  • 你的控制台告诉你什么?
  • 没什么,它似乎有效 :) ([Document about:blank] from firebug)

标签: javascript jquery iframe


【解决方案1】:

填充框架内容的最佳方式是document.write

var dstFrame = document.getElementById('yourFrameId');
var dstDoc = dstFrame.contentDocument || dstFrame.contentWindow.document;
dstDoc.write(yourHTML);
dstDoc.close()

UPD:即

var iFrame = $('<iframe id="thepage"></iframe>');
$('body').append(iFrame);

var iFrameDoc = iFrame[0].contentDocument || iFrame[0].contentWindow.document;
iFrameDoc.write('<p>Some useful html</p>');
iFrameDoc.close();

【讨论】:

    【解决方案2】:

    如果你想避免使用document.write,一般不再推荐,你可以在框架内容处添加内容:

    iframe = $('<iframe id="thepage"></iframe>')
    iframeHtml = 'iframeHtml'
    $('body').append(iframe)
    iframe.contents().find('body').html(iframeHtml)
    

    【讨论】:

      【解决方案3】:

      使用 JQuery,您可以通过将 html 作为字符串传递给 iframe 的属性 srcdoc

      $('#iframe_id').attr("srcdoc", htmlString);
      

      【讨论】:

      • 这很好,虽然它不会在里面加载任何脚本标签。
      【解决方案4】:
      iframe = $('<iframe id="thepage"></iframe>');
      
      iframeHtml = 'iframeHtml'; $('body').append(iframe);
      
      iframe .contents() .html(iframeHtml);
      

      它不起作用的原因是因为contents() 返回一个document 对象,而html() 仅适用于HTMLElemnt 对象,html() 基本上是innerHTML 属性的包装器,而document 不有这样的属性。

      【讨论】:

        【解决方案5】:

        使用 jQuery contents() 方法 您可以结合使用 jQuery contents() 方法与 find()、val() 和 html() 方法在 iframe 正文中插入文本或 HTML。

        var EditFrame = $("#EditWindow").contents().find('body');
        var message = "Your message which needs to show in Iframe";
        EditFrame.html(message);

        【讨论】:

          猜你喜欢
          • 2011-04-18
          • 2013-02-15
          • 2013-05-13
          • 2015-07-12
          • 2021-09-02
          • 1970-01-01
          • 2015-03-31
          • 2013-06-22
          • 1970-01-01
          相关资源
          最近更新 更多