替换Iframe的整个内容

Eri*_*ott 15 javascript iframe jquery

有没有办法用Javascript(或Jquery)替换iframe的整个内容?

例如,如果我的iframe有以下内容......

blah outside of html
<html>
<head>
</head>
<body>
<h1> my title </h1>
</body>
</html>
blah outside of html
Run Code Online (Sandbox Code Playgroud)

..它可以全部被你的脚本取代:)

到目前为止我见过的最好的是:

$(youriframe).contents().find('html').html('your content here'); 
Run Code Online (Sandbox Code Playgroud)

但是仍然不会替换html标签之外的内容.我们有一个有趣的场景,我们必须确保所有内容都被替换.

或者创建一个包含新内容的新iframe,并简单地替换以前的iframe.

请不要评论src属性.

YuC*_*YuC 20

我有同样的问题,如果我使用这样的代码:

$(youriframe).contents().find('html').html('your content here'); 
Run Code Online (Sandbox Code Playgroud)

它在Chrome或FireFox中运行良好,但在IE8中,不显示任何内容或iframe中的滚动条不会出现.

如果我使用Rachel的方法,iframe内容在所有浏览器中都是这样的:

<iframe>
    <html>
        <head>
        </head>
        <body>
        </body>
    </html>
</iframe>
Run Code Online (Sandbox Code Playgroud)

还有其他解决方案吗?

尝试过这个:

var doc = document.getElementById(iframeId).contentWindow.document;
doc.open();
doc.write(iframeContent);
doc.close();
Run Code Online (Sandbox Code Playgroud)

这适用于我的情况,ie8和FF/chrome.


Jam*_*day 14

我猜你在这个例子中没有跨站脚本问题...你有没有运气使用contentWindow?像这样的东西对我来说似乎运作得很好:

iframe = document.getElementById('iframe_id');
iframe.contentWindow.document.open()
iframe.contentWindow.document.write(new_content_here);
Run Code Online (Sandbox Code Playgroud)

不是我的想法,在这里找到它:使用Javascript或jQuery将元素写入子iframe


小智 -3

有一个类似的场景,每次单击表的行时,我都会生成一个新的 iFrame,其中包含来自不同域的内容。

为此,我使用 jQuery AJAX 和 PHP。PHP 查看我的 MySQL 表并获取我想要加载的 iFrame 的 URL;它为 iFrame 生成 HTML,我使用 jQuery AJAX 来替换该内容。

我的 HTML 看起来像这样:

<div class="xFrame">
    <iframe id="xFrameWindow" name="xFrameWindow" src=""></iframe>
</div>
Run Code Online (Sandbox Code Playgroud)

我的 AJAX 调用如下所示:

函数loadPage(record_id) {

    $.ajax({
        类型:“帖子”,
        url: "php/ajax_handler.php",
        数据:“action=makeIFrame&record_id=”+record_id,
        成功:函数(消息){
            $('.xFrame' ).html(msg);
        }
    });
}

该代码将包含 iFrame 的 div 的 HTML 替换为新的 iFrame。

希望这个(或类似的东西)对你有用。