将子 iframe 中的事件附加到父窗口中的处理程序 [英] Attach an event in a child iframe to a handler in the parent window

查看:36
本文介绍了将子 iframe 中的事件附加到父窗口中的处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法直接访问此 iframe 的源代码,因此如果可能的话,我想这样做.

I don't have access to this iframe's source directly, so I would like to do this, if it's possibly this way.

我有一个由 JS 生成的 iframe:

I have an iframe generated by JS:

<iframe name="temp_iframe" width="100%" height="95%" src="'+the_url+'"></iframe>

里面有一个提交按钮和一个取消按钮.提交按钮工作正常,但我希望取消按钮关闭这个包含 iframe 的模式......我还希望提交按钮发送,然后关闭模式.通常这很容易,但我不确定如何在父窗口中将事件设置为影响子父窗口的 iframe 子 DOM 元素.

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, then close 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 和 jQuery 中:

E.g. if this wasn't in an iframe and in jQuery:

$('[name=temp_iframe] button').live('click',function(){
    alert('click');
    return false;
});

而且,它在同一个域中!

And also, it's on the same domain!

推荐答案

使用 contents() 访问 iframe 内的 Document 对象.请注意,在一个文档中使用 jQuery 库来操作另一个文档通常会出现问题,通常应该避免这种情况.但是,在绑定事件的情况下,它确实有效.

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.

$('[name=temp_iframe]').contents().find('button').click(function() {
    alert('click');
});

这需要加载 iframe 及其内容,因此如有必要,请在 $(window).load() 处理程序中执行此操作.您不能跨文档live/delegate,因为事件不会从子文档传播到其父文档.

This requires that the iframe and its contents are loaded, so do it in a $(window).load() handler if necessary. You can't live/delegate across documents, as events don't propagate from a child document into its parent.

这篇关于将子 iframe 中的事件附加到父窗口中的处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆