Javascript 从 iframe 访问和更改父页面(使用 jquery)

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

access and change parent page from iframe (with jquery)

javascriptjqueryhtmliframe

提问by Dan

is there any way how to access from iframe to parrent page (and change parrent page)?

有什么方法可以从 iframe 访问父页面(并更改父页面)?

<body>
   <iframe src="frame1.html" name="frame1" height="100%"></iframe>
   <div id="test1"></div>
</body>

In frame1.html is <a href=..>and I want to add text "<h1>clicked</h1>" into <div id="test1"></div>, when the <a href..>was clicked.

在 frame1.html 中<a href=..>,我想在单击时将文本“ <h1>clicked</h1>”添加到 中。<div id="test1"></div><a href..>

Thanks.

谢谢。

回答by naota

If your child page (frame1.html) is located at the same domain as the parent page, You can write a code like below in the child window :

如果您的子页面(frame1.html)与父页面位于同一域,您可以在子窗口中编写如下代码:

 $('#test1', parent.document).html('<h1>clicked</h1>');

The second parameter provides the contextin which to search the element matched by the first parameter. The Document is here:http://api.jquery.com/jQuery/#jQuery-selector-context

第二个参数提供了context搜索与第一个参数匹配的元素的位置。文档在这里:http: //api.jquery.com/jQuery/#jQuery-selector-context

 jQuery( selector [, context ] )

So, your code (frame1.html) could go like this:

所以,你的代码 (frame1.html) 可能是这样的:

 <a href="..." 
  onclick="$('#test1', parent.document).html('<h1>clicked</h1>');">click me</a>

Hope this helps.

希望这可以帮助。

回答by Christoph

Important note:Accessing in and out iframes is only possible, if both, parent and iframe are from the same domain, else you have no access due to Same Origin Policy.

重要提示:访问进出I帧才有可能,如果双方,父母和iframe都来自同一个域,否则你会有进不去同源策略

Note, that both parts have their own document. Accessing the parent object from iframe is simple with

请注意,这两个部分都有自己的文档。从 iframe 访问父对象很简单

parent.document

and from parent it is one of the following:

来自父级,它是以下之一:

window.frames['iframeName']

(window.frames.length /*gives you the number of iframes in your document*/ )

or reference it with id and do the following (watch out for support!)

或使用 id 引用它并执行以下操作(注意支持!)

var iframe = document.getElementById('iframe');
var doc = iframe.contentDocument? iframe.contentDocument:iframe.contentWindow.document;

回答by Teja

The code below should work fine:

下面的代码应该可以正常工作:

$(parent.document).find("#selector");

The selector is from the parent document to perform some action. For Example:

选择器是从父文档中执行一些动作。例如:

$(parent.document).find("#selector").remove();