如何使用jQuery公开IFrame的DOM? [英] How to expose IFrame's DOM using jQuery?
问题描述
我的问题是:如何创建一个InternalDOM属性使该属性引用到IFrame的窗口对象(根DOM对象)?这样:如果我的IFrame公开了一个页面,其中有一个对象X在它的窗口对象中,我可以做:
MyFrameObject.GoToUrl(pageXurl);
MyFrameObject.InternalDOM.X
任何帮助将不胜感激。
PS:我会接受不一定与jQuery相关的答案,但我更喜欢一个jQuery解决方案。
要获取框架的窗口
对象,您可以使用 window.frames
array:
var iframewindow = frames ['iframe_name'];
这需要你给< iframe>
一个老式的名称
属性代替或者一样好,就像 id
一样。或者,如果您知道页面上iframes的顺序,您可以按数字索引:
var iframewindow = frames [0];从DOM中的iframe元素获取iframe窗口通常更为灵活,但这需要一些功能。兼容性代码来处理IE: var iframe = document.getElementById('iframe_id');
var iframewindow = iframe.contentWindow? iframe.contentWindow:iframe.contentDocument.defaultView;
jQuery定义了 contents()方法来抓取文档
节点,但它并没有给你一个跨浏览器的方式从文件
到窗口
,所以你仍然坚持:
var iframe = $('#iframe_id')[0];
var iframewindow = iframe.contentWindow? iframe.contentWindow:iframe.contentDocument.defaultView;
这不是一个大赢家。
(注意:使用jQuery进行跨框架脚本,每个框架都需要自己的jQuery副本,而一帧的副本中的方法不一定在另一个节点上工作,跨框架脚本是主题充满陷阱。)
I have a prototype representing a particual IFrame. That prototype have a function called GoToUrl(...) that opens the given url within the IFrame.
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
Any help would be appreciated.
PS: I would accept answers not necessarily related to jQuery but I would prefer a jQuery solution.
解决方案 To get the window
object for a frame you can use the window.frames
array:
var iframewindow= frames['iframe_name'];
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];
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 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.
(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屋!