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

查看:21
本文介绍了如何将 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.

请注意,您应该使用 contentWindow.document.write 而不是 contentDocument.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天全站免登陆