Javascript 将子 iframe 中的事件附加到父窗口中的处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3672726/
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
Attach an event in a child iframe to a handler in the parent window
提问by Oscar Godson
I don't have access to this iframe's source directly, so I would like to do this, if it's possibly this way.
我无法直接访问这个 iframe 的源代码,所以我想这样做,如果可能的话。
I have an iframe generated by JS:
我有一个由 JS 生成的 iframe:
<iframe name="temp_iframe" width="100%" height="95%" src="'+the_url+'"></iframe>
And inside is a submit button and a cancel button. The submit button works fine, but I want the cancel button to close this modal that is containing the iframe... I also want the submit button to send, thenclose the modal. Normally this would be easy, but im not sure how to setup an event in the parent window to a child DOM element of the iframe that affects the child's parent, the main window.
里面是一个提交按钮和一个取消按钮。提交按钮工作正常,但我希望取消按钮关闭这个包含 iframe 的模式......我也希望提交按钮发送,然后关闭模式。通常这很容易,但我不确定如何在父窗口中将事件设置为影响子父窗口的 iframe 子 DOM 元素。
E.g. if this wasn't in an iframe and in jQuery:
例如,如果这不在 iframe 和 jQuery 中:
$('[name=temp_iframe] button').live('click',function(){
alert('click');
return false;
});
EDIT: And also, it's on the same domain!
编辑:而且,它在同一个域上!
回答by bobince
Use contents()to access the Document object inside an iframe. Note that there are in general problems with using a jQuery library in one document to manipulate another document and it should in general be avoided. However, in the case of binding events it does work.
使用contents()访问文档对象的iframe内。请注意,在一个文档中使用 jQuery 库来操作另一个文档通常存在问题,通常应该避免。但是,在绑定事件的情况下,它确实有效。
$('[name=temp_iframe]').contents().find('button').click(function() {
alert('click');
});
This requires that the iframe and its contents are loaded, so do it in a $(window).load()handler if necessary. You can't live/delegateacross documents, as events don't propagate from a child document into its parent.
这需要加载 iframe 及其内容,因此$(window).load()如有必要,请在处理程序中执行此操作。您不能live/delegate跨文档,因为事件不会从子文档传播到其父文档。
回答by mjaque
In plain JavaScript it would be:
在纯 JavaScript 中,它将是:
document.getElementById("frameId").contentDocument.getElementById("buttonId").click();
If you need to search elements by attribute value and tag name, you can:
如果您需要按属性值和标签名称搜索元素,您可以:
document.querySelectorAll('[name=temp_iframe]')[0].contentDocument.getElementsByTagName('button')[0].click();

