[英]Attach an event in a child iframe to a handler in the parent window
我没有直接访问这个iframe的源代码,所以我想这样做,如果可能的话。
我有一个由JS生成的iframe:
<iframe name="temp_iframe" width="100%" height="95%" src="'+the_url+'"></iframe>
里面是提交按钮和取消按钮。 提交按钮工作正常,但我希望取消按钮关闭包含iframe的此模式...我还希望提交按钮发送, 然后关闭模式。 通常这很容易,但我不知道如何在父窗口中将事件设置为iframe的子DOM元素,该元素会影响子窗口的父窗口(主窗口)。
例如,如果这不是在iframe和jQuery中:
$('[name=temp_iframe] button').live('click',function(){
alert('click');
return false;
});
编辑:而且,它在同一个域名!
使用contents()
访问iframe中的Document对象。 请注意,在一个文档中使用jQuery库来操作另一个文档通常存在一些问题,通常应避免使用它。 但是,在绑定事件的情况下,它确实有效。
$('[name=temp_iframe]').contents().find('button').click(function() {
alert('click');
});
这需要加载iframe及其内容,如果需要,也可以在$(window).load()
处理程序中加载。 您不能跨文档live
/ delegate
,因为事件不会从子文档传播到其父文档。
在纯JavaScript中它将是:
document.getElementById("frameId").contentDocument.getElementById("buttonId").click();
如果需要按属性值和标记名称搜索元素,则可以:
document.querySelectorAll('[name=temp_iframe]')[0].contentDocument.getElementsByTagName('button')[0].click();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.