将html放在iframe中(使用javascript)

has*_*sen 33 html javascript iframe jquery

我可以创建一个空的iframe作为占位符,以便稍后将html插入其中吗?

换句话说,假设我有一个带id的空iframe,

如何在其中插入html?

我正在使用jquery,如果这更容易.

Bla*_*nic 40

你也可以在没有jQuery的情况下做到:

var iframe = document.getElementById('iframeID');
iframe = iframe.contentWindow || ( iframe.contentDocument.document || iframe.contentDocument);

iframe.document.open();
iframe.document.write('Hello World!');
iframe.document.close();
Run Code Online (Sandbox Code Playgroud)

jQuery的html从插入的HTML中删除body,html和head标签.

  • `iframe = iframe.contentWindow || (iframe.contentDocument.document || iframe.contentDocument);` (3认同)

Tys*_*son 36

查看此页面的来源:http://mg.to/test/dynaframe.html它似乎完全符合您的要求.

$(function() {
    var $frame = $('<iframe style="width:200px; height:100px;">');
    $('body').html( $frame );
    setTimeout( function() {
        var doc = $frame[0].contentWindow.document;
        var $body = $('body',doc);
        $body.html('<h1>Test</h1>');
    }, 1 );
});
Run Code Online (Sandbox Code Playgroud)


小智 9

不,这不对.您可以像这样修改脚本:

$(function() {
    var $frame = $('iframe');
    setTimeout( function() {
            var doc = $frame[0].contentWindow.document;
            var $body = $('body',doc);
            $body.html('<h1>Test</h1>');
    }, 1 );
});
Run Code Online (Sandbox Code Playgroud)


Ort*_*iel 5

iframeElementContainer =   document.getElementById('BOX_IFRAME').contentDocument;
iframeElementContainer.open();
iframeElementContainer.writeln("<html><body>hello</body></html>");
iframeElementContainer.close();
Run Code Online (Sandbox Code Playgroud)