如何使用 jQuery 公开 IFrame 的 DOM? [英] How to expose IFrame's DOM using jQuery?
问题描述
我有一个代表特定 IFrame 的原型.该原型有一个名为 GoToUrl(...) 的函数,用于在 IFrame 中打开给定的 url.
I have a prototype representing a particual IFrame. That prototype have a function called GoToUrl(...) that opens the given url within the IFrame.
我的问题是:如何创建InternalDOM"属性并使该属性引用内部 IFrame 的窗口"对象(根 DOM 对象)?以这样的方式:如果我的 IFrame 公开了一个页面,该页面在它的窗口"对象中有一个对象 X,我可以这样做:
My question is: How do I create an "InternalDOM" property and make this property refer to the "window" object (the root DOM object) of the IFrame inside? In such way that: If my IFrame exposes a page which has an object X in it's "window" object I could do:
MyFrameObject.GoToUrl(pageXurl);
MyFrameObject.InternalDOM.X
任何帮助将不胜感激.
PS:我会接受不一定与 jQuery 相关的答案,但我更喜欢 jQuery 解决方案.
PS: I would accept answers not necessarily related to jQuery but I would prefer a jQuery solution.
推荐答案
要获取框架的 window
对象,您可以使用 window.frames
数组:>
To get the window
object for a frame you can use the window.frames
array:
var iframewindow= frames['iframe_name'];
这要求你给 一个老式的
name
属性而不是 id代码>.或者,如果您知道页面上 iframe 的顺序,您可以用数字索引它们:
This requires that you give the <iframe>
an old-school name
attribute instead-of-or-as-well-as the id
. Alternatively if you know the order of iframes on the page you can index them numerically:
var iframewindow= frames[0];
从DOM中的iframe元素获取iframe窗口一般更灵活,但这需要一些兼容代码来应对IE:
It's generally more flexible to get the iframe window from the iframe element in the DOM, but this requires some compatibility code to cope with IE:
var iframe= document.getElementById('iframe_id');
var iframewindow= iframe.contentWindow? iframe.contentWindow : iframe.contentDocument.defaultView;
jQuery 定义了 contents() 方法来抓取 document
节点,但它没有为您提供从 document
到 window
的跨浏览器方式,因此您仍然坚持:
jQuery defines the contents() method to grab the document
node, but it doesn't give you a cross-browser way to go from the document
to the window
, so you're still stuck with:
var iframe= $('#iframe_id')[0];
var iframewindow= iframe.contentWindow? iframe.contentWindow : iframe.contentDocument.defaultView;
这并不是一个很大的胜利.
which isn't really a big win.
(注意:使用 jQuery 进行跨框架脚本编写时要非常小心.每个框架都需要自己的 jQuery 副本,一个框架副本中的方法不一定适用于另一个框架的节点.跨框架脚本是一种充满陷阱的话题.)
(Note: be very careful using jQuery for cross-frame-scripting. Each frame needs its own copy of jQuery and methods from one frame's copy won't necessarily work on nodes from the other. Cross-frame-scripting is a topic fraught with traps.)
这篇关于如何使用 jQuery 公开 IFrame 的 DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!