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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:10:57  来源:igfitidea点击:

Get reference of window object from a dom element

javascriptjquery

提问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 ownerDocumentproperty to get a reference to the document, then read its defaultViewproperty (parentWindowfor 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;