将 html 放在 iframe 中(使用 javascript)

IT技术 javascript jquery html iframe
2021-01-15 18:39:35

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

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

如何在其中插入 html?

我正在使用 jquery,如果这样更容易的话。

6个回答

你也可以在没有 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();

jQuery 的 html 从插入的 HTML 中去除 body、html 和 head 标签。

iframe = iframe.contentWindow || ( iframe.contentDocument.document || iframe.contentDocument);
2021-04-05 18:39:35
这是正确答案。<html foo="bar"></html>. 请注意,iframe 必须插入到其父文档中。
2021-04-10 18:39:35
从 AJAX 请求加载“document.write”脚本时,工作就像一个魅力
2021-04-13 18:39:35
这不是正确的方法。这没有任何功能。
2021-04-13 18:39:35

查看此页面的来源: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 );
});
这只会body在您可能需要元素时复制元素,head甚至是html元素的属性
2021-03-23 18:39:35

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

$(function() {
    var $frame = $('iframe');
    setTimeout( function() {
            var doc = $frame[0].contentWindow.document;
            var $body = $('body',doc);
            $body.html('<h1>Test</h1>');
    }, 1 );
});
为什么要设置超时?
2021-04-06 18:39:35
iframeElementContainer =   document.getElementById('BOX_IFRAME').contentDocument;
iframeElementContainer.open();
iframeElementContainer.writeln("<html><body>hello</body></html>");
iframeElementContainer.close();

是的,我知道这是可能的,但主要问题是我们无法从外部处理框架,我已经加载了其他一些东西。

$(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 );
});

但如果我们开始

<iframe src="http:/www.hamrobrt.com">
<---Your Script to put as you like--->

那么它不可能击中那个。