【问题标题】:Replacing entire contents of iframe (including doctype & html tags) with jQuery用 jQuery 替换 iframe 的全部内容(包括 doctype 和 html 标签)
【发布时间】:2012-07-04 03:13:21
【问题描述】:

stackoverflow 上还有很多其他帖子提出了几乎相同的问题,但在我迄今为止阅读的所有答案中,它们并没有解决如何从本质上替换 iframe 的整个文档,包括 DOCTYPE和html标签。

我正在通过 jQuery.ajax 请求检索整个页面的 HTML,并尝试将返回的 HTML 用作 iframe 的新 HTML。下面是从 ajax 请求返回的 HTML 示例:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <link rel="stylesheet" type="text/css" media="all" href="main.css">
        <title>Test Page</title>
    </head>
    <body>
        <h1>Heading</h1>
    </body>
</html>

然后我通过以下方式将该 HTML 注入 iframe:

$('#my-iframe').contents().find('html').html(returnedHtml);

正如关于此主题的大多数其他帖子所建议的那样。但是,当我检查 iframe 的内容时,文档的结构如下:

<html>
    <link rel="stylesheet" type="text/css" media="all" href="main.css">
    <title>Test Page</title>
    <h1>Heading</h1>
</html>

请注意缺少 DOCTYPE、html 标记上缺少 lang 属性、缺少 head 和 body 标记。

有什么建议吗? (请注意,由于各种因素,在此应用中仅将 iframe 的 src 属性更改为必要的 url 是不可能的)

【问题讨论】:

    标签: jquery ajax iframe


    【解决方案1】:

    尝试一些普通的 javascript:

    iframe = document.getElementById('my-iframe');
    iframe.contentWindow.document.open()
    iframe.contentWindow.document.write(returnedHtml);​
    

    FIDDLE

    【讨论】:

    • 看起来可以在 Chrome 中使用,这可以跨浏览器可靠地工作吗? (或至少 IE8+、Firefox、Chrome、Safari)
    • 不确定,没有在所有浏览器中测试过,但至少在 Chrome 和 FF 中工作过。
    猜你喜欢
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2022-12-08
    • 1970-01-01
    • 2014-06-13
    • 2011-11-03
    相关资源
    最近更新 更多