替换 iframe 文档的 HTML 源代码

Replacing HTML source of an iframe document

本文关键字:HTML 源代码 文档 iframe 替换      更新时间:2023-09-26

我正在处理一个将显示数据库字段内容的页面。内容采用 HTML 格式,包括整个网页

<html>
  <title>Some title</title>
  <style type="text/css">
     /* CSS content here */
  </style>
  <body>
    <!-- body content here -->
  </body>
</html>

我需要在另一个网页中显示所有这些内容,所以我认为使用 iframe 可以让我否定父页面中的任何 css。 但是,我不知道如何覆盖iframe文档的内容。

到目前为止,我所做的是检索数据,然后使用以下方法

$("#iframe_constainer")
  .find('iframe:first').contents().find('html:first').html(myHTML);

我的网页包含一个名为 iframe_container 的div,其中包含一个 iframe。

<div id="iframe_container"><iframe/></div>

这工作正常,但myHTML的内容被包装在html标签中。 所以效果是这样的

<html>
  <html>
    <title>Some title</title>
    <style type="text/css">
       /* CSS content here */
    </style>
    <body>
      <!-- body content here -->
    </body>
  </html>
</html>

我知道这是因为我在 iframe 中找到了 html 标签并更改了 HTML。 有没有办法使用 jQuery 覆盖整个文档?

打开文档并在之后关闭将解决附加内容的问题

var iframe = document.getElementById('iframeID');
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(htmlData);
iframe.contentWindow.document.close();

你真的不需要jQuery,只需使用document.write将内容写入iframe即可完全替换iframe的文档。

例如(在普通的香草JS中)

document.getElementById("myIframeId").contentWindow.document.write(myHTML);