如何将HTML内容设置为iframe [英] How to set HTML content into an iframe

查看:178
本文介绍了如何将HTML内容设置为iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML字符串

I have a HTML string

<html>
  <body>Hello world</body>
</html> 

我希望用JavaScript将其设置为iframe。我试图像这样设置HTML:

and I want to set it to an iframe with JavaScript. I am trying to set the HTML like this:

contentWindow.document.body.innerHTML

contentDocument.body.innerHTML

document.body.innerHTML

但IE给出访问被拒绝。或对象不支持此属性或方法。或动作的最终元素无效。错误。

but IE gives "Access is denied." or "Object does not support this property or method." or "Invalid final element to the action." errors.

这是我的完整代码:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="jquery_1.7.0.min.js"/>
    <script type="text/javascript">
      $(document).ready(function(){
        var htmlString = "<html><body>Hello world</body></html>";
        var myIFrame = document.getElementById('iframe1');
        // open needed line commentary
        //myIFrame.contentWindow.document.body.innerHTML = htmlString;
        //myIFrame.contentDocument.body.innerHTML = htmlString;
        //myIFrame.document.body.innerHTML = htmlString;
        //myIFrame.contentWindow.document.documentElement.innerHTML = htmlString;
      });
    </script>
  </head>
  <body>
    <p>This is iframe:
      <br>
      <iframe id="iframe1">
      <p>Your browser does not support iframes.</p>
      </iframe>
  </body>
</html>


推荐答案

您可以使用:

document.getElementById('iframe1').contentWindow.document.write("<html><body>Hello world</body></html>");

这是 jsFiddle ,适用于所有主流浏览器。

Here's a jsFiddle, which works in all major browsers.

请注意,而不是 contentDocument.write 你应该使用 contentWindow.document.write :这也使它在IE7中工作。

Note that instead of contentDocument.write you should use contentWindow.document.write: this makes it work in IE7 as well.

这篇关于如何将HTML内容设置为iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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