jQuery 在父窗口中选择元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6017796/
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 20:14:36  来源:igfitidea点击:

jQuery select element in parent window

jqueryjquery-selectorspopupparent

提问by Rob

Is there a way to select a DIV in the parent window using jQuery?

有没有办法使用jQuery在父窗口中选择一个DIV?

For example:

例如:

Main page contains this,

主页包含这个,

<div id="testdiv"></div>

Popup page has a form with some options and an 'Apply' button. When the user clicks apply it affects the style attribute on the main page.

弹出页面有一个带有一些选项的表单和一个“应用”按钮。当用户单击应用时,它会影响主页上的样式属性。

Something along the logic of,

沿着逻辑的东西,

parent.$("#testdiv").attr("style", content from form);

回答by Dr.Molle

Use the context-parameter

使用上下文参数

$("#testdiv",parent.document)

But if you really use a popup, you need to access openerinstead of parent

但是如果你真的使用弹出窗口,你需要访问opener而不是parent

$("#testdiv",opener.document)

回答by TARKUS

I looked for a solution to this problem, and came across the present page. I implemented the above solution:

我寻找解决此问题的方法,并遇到了当前页面。我实施了上述解决方案:

$("#testdiv",opener.document) //doesn't work

But it doesn't work. Maybe it did work in previous jQuery versions, but it doesn't seem to work now.

但它不起作用。也许它在以前的 jQuery 版本中确实有效,但现在似乎不起作用。

I found this working solution on another stackoverflow page: how to access parent window object using jquery?

我在另一个 stackoverflow 页面上找到了这个可行的解决方案: 如何使用 jquery 访问父窗口对象?

From which I got this working solution:

我从中得到了这个工作解决方案:

window.opener.$("#testdiv") //This works.

回答by crodriguez

I came across the same problem but, as stated above, the accepted solution did not work for me.

我遇到了同样的问题,但如上所述,接受的解决方案对我不起作用。

If you're inside a frame or iframe element, an alternative solution is to use

如果您在框架或 iframe 元素内,另一种解决方案是使用

window.parent.$('#testdiv');

Here's a quick explanation of the differences between window.opener, window.parent and window.top:

下面是对 window.opener、window.parent 和 window.top 之间差异的快速解释:

  • window.opener refers to the window that called window.open( ... ) to open the window from which it's called
  • window.parent refers to the parent of a window in a frame or iframe element
  • window.opener 指的是调用 window.open( ... ) 打开调用它的窗口的窗口
  • window.parent 指的是 frame 或 iframe 元素中窗口的父级

回答by Jashwant

You can also use,

您还可以使用,

parent.jQuery("#testdiv").attr("style", content from form);

parent.jQuery("#testdiv").attr("style", content from form);

回答by Thomas Smart

why not both to be sure?

为什么不两者都确定?

if(opener.document){
  $("#testdiv",opener.document).doStuff();
}else{
  $("#testdiv",window.opener).doStuff();
}