【问题标题】:Attach an event in a child iframe to a handler in the parent window将子 iframe 中的事件附加到父窗口中的处理程序
【发布时间】:2011-04-10 00:28:30
【问题描述】:

我无法直接访问此 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;
});

编辑:而且,它在同一个域上!

【问题讨论】:

  • 如果 iframe 的来源是另一个域,由于跨站脚本限制,您不能这样做。
  • 它是同一个域...我只是没有访问权限。我在俄勒冈州波特兰市工作,我必须请求更改服务器端代码...
  • 建议标题更改:将子 iframe 中的事件附加到父窗口中的处理程序。当前的措辞听起来好像您想.trigger() 孩子中的一个事件。这种混淆导致在a question that does use trigger 上出现错误的重复关闭投票。

标签: javascript jquery html events iframe


【解决方案1】:

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

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

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

【讨论】:

  • 完美!谢谢!我把它放在了 .load('iframe') 中
【解决方案2】:

在纯 JavaScript 中是:

document.getElementById("frameId").contentDocument.getElementById("buttonId").click();

如果需要按属性值和标签名搜索元素,可以:

document.querySelectorAll('[name=temp_iframe]')[0].contentDocument.getElementsByTagName('button')[0].click();

【讨论】:

    猜你喜欢
    • 2018-02-15
    • 2018-03-18
    • 2016-05-30
    • 2012-10-23
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多