替换Iframe的整个内容 [英] Replace Entire Content of Iframe

查看:164
本文介绍了替换Iframe的整个内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to replace the ENTIRE contents of an iframe using Javascript (or Jquery)?

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

For example if my iframe had the following content...

blah outside of html
<html>
<head>
</head>
<body>
<h1> my title </h1>
</body>
</html>
blah outside of html

..它们都可以被你的脚本取代:)

..It could all be replaced by your script :)

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

The best that I've seen so far is this:

$(youriframe).contents().find('html').html('your content here'); 

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

but that still wouldn't replace the content outside of the html tags. We have an interesting scenario where we must assure that ALL the content is replaced.

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

OR a new iframe with fresh content is created and simply replaces the previous iframe.

请不要评论src属性。

Please no comments about the src attribute.

推荐答案

我遇到了同样的问题,如果我使用这样的代码:

I am having the same issue, and if i use the code like this:

$(youriframe).contents().find('html').html('your content here'); 

在Chrome或FireFox中工作正常,但在IE8中,不会显示任何内容或滚动条在iframe不会出现。

It works fine in Chrome or FireFox, but in IE8, nothing will be showed or the scroll bar in iframe won't appear.

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

If i use Rachel's method, the iframe content will be like this in all browsers:

<iframe>
    <html>
        <head>
        </head>
        <body>
        </body>
    </html>
</iframe>

还有其他解决方案吗?

试过这个:

var doc = document.getElementById(iframeId).contentWindow.document;
doc.open();
doc.write(iframeContent);
doc.close();

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

this works on my case, both ie8 and FF/chrome.

这篇关于替换Iframe的整个内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆