jQuery 从 dom 元素获取 window 对象的引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16010204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get reference of window object from a dom element
提问by Aniket
I have a javascript code like this
我有一个这样的 javascript 代码
var element = $("elementId");
I got the reference to the element (which is a div).
我得到了对元素的引用(这是一个 div)。
Now I need to get the reference to the window in which this div element resides. But the problem is, here the $ is passed from a different window. So now the element resides in a different window.
现在我需要获取对这个 div 元素所在的窗口的引用。但问题是,这里的 $ 是从不同的窗口传递的。所以现在元素驻留在不同的窗口中。
How to get reference to that window object which contains this div element? Pls Help.
如何获取对包含此 div 元素的窗口对象的引用?请帮助。
回答by Rob W
Get a reference to the DOM node, use the ownerDocument
property to get a reference to the document, then read its defaultView
property (parentWindow
for IE8-) to get a reference to the window:
获取DOM节点的引用,使用ownerDocument
属性获取文档的引用,然后读取其defaultView
属性(parentWindow
对于IE8-)获取窗口的引用:
var $element = $('#elementId');
var element = $element[0];
// Assume that element exists, otherwise an error will be thrown at the next line
var doc = element.ownerDocument;
var win = doc.defaultView || doc.parentWindow;