【问题标题】:Accessing Elements Inside iframe and body Tags with JavaScript使用 JavaScript 访问 iframe 和 body 标签内的元素
【发布时间】:2012-07-01 22:16:54
【问题描述】:

我正在编写一个 GreaseMonkey 脚本,该脚本修改具有特定 ID 的元素的属性,但由于非传统的 HTML 层次结构,我在访问它时遇到了一些问题。这是相关的 HTML:

<body>
...
    <iframe id="iframeID">
        <html>
        ...
            <body id="bodyID" attribute="value">
            ...
            </body>
        ...
        </html>
    </iframe>
...
</body> 

attribute 是我尝试修改的属性。

起初,我没有意识到我正在使用iframe 和嵌套的body 标签,我尝试了这个:

document.getElementById('bodyID').setAttribute("attribute","value")

虽然这在 Firefox 中运行良好,但 Chrome 告诉我我无法设置 null 的属性,这表明它找不到任何 ID 为 bodyID 的元素。如何以跨浏览器友好的方式修改此属性?

【问题讨论】:

  • 你试过window.frames吗? (文档:developer.mozilla.org/en/DOM/window.frames
  • @drderp 虽然我认为这可行,但与 gdoron 的解决方案相比,代码会包含不必要的混乱。
  • gdoron 在我发布我的解决方案后立即发布了他的解决方案;我同意你的看法。
  • 查看我对 &lt;body&gt; 的更新 + 演示。

标签: javascript html dom iframe cross-browser


【解决方案1】:

IMO 最好的方法是监听 iFrame 触发的 load 事件,然后根据需要查看 iFrame DOM。这可以保证您在需要时可以使用 iFrame DOM 并花点时间。

$('#iframeID').on('load', function ()
{
  alert('loaded'); // iFrame successfully loaded
  var iFrameDoc = $('#iframeID')[0].contentDocument; // Get the iFrame document
  $('body', iFrameDoc).attr('attribute', 'new value'); // Get the 'body' in the iFrame document and set 'attribute' to 'new value'
});

【讨论】:

  • jQuery 标签在哪里?并阅读我对&lt;body&gt; 的评论
  • @gdoron,在你的 中添加 jQuery。如果 iFrame 和 iFrame 容器由于跨域策略而具有不同的域,这将不起作用。
  • 不确定您对 jQuery 的意思。并且您的答案与跨域策略有相同的问题。
【解决方案2】:

首先需要拉取&lt;iframe&gt;的文档:

document.getElementById('iframeID').contentDocument
.getElementById('bodyID').setAttribute("attribute","value");

Live DEMO

顺便说一句,如果你想获得 &lt;body&gt; 节点,你不需要提供 id 或类似的东西,只需:

document.body

在你的情况下,它是&lt;iframe&gt;的文档:

document.getElementById('iframeID').contentDocument.body.setAttribute("attribute","value");

简单多了...不是吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2011-12-09
    • 2010-11-29
    • 2019-05-17
    • 2012-10-01
    • 2023-04-11
    • 2015-03-12
    相关资源
    最近更新 更多