【问题标题】:Trigger events in iframe's parent window在 iframe 的父窗口中触发事件
【发布时间】:2011-06-03 19:59:25
【问题描述】:

为什么以下不起作用:

//iframe:
window.parent.$(document).trigger('complete');

//parent window:
$(document).bind('complete', function(){
  alert('Complete');
});

当以下工作正常时:

//iframe:
window.parent.$('body').trigger('complete');

//parent window:
$('body').bind('complete', function(){
  alert('Complete');
});

?

【问题讨论】:

标签: javascript jquery jquery-events


【解决方案1】:

事件的跟踪方式,只能在同一个文档上触发或接收事件。

试试

window.parent.$(window.parent.document).trigger('complete');

【讨论】:

  • 我在使用 YUI3 时也遇到了同样的问题,有什么建议吗?
  • @Danjah 我以前从未真正使用过 YUI,所以我不确定我是否能提供帮助。但是,完全有可能使用类似的方法:window.parent.YUI.use('node-event-simulate', function(Y) { Y.one(window.parent.document).simulate('click '); });但是,您可能只想在父级上公开一个方法来代表您的 iframe 执行所需的触发,下面是 @Ken Redler 的建议。
  • 好的,非常感谢 - 我一定会好好庆祝一下,在尝试触发现有处理程序之前开始模拟事件有点谨慎......但我可能不得不这样做。
  • +1 正是我需要的!我想从我的 iframe 中触发父窗口的调整大小事件。
  • 我想特别指出(因为我花了一秒钟才明白)问题在于document 指的是window.document,即iframe 的document。要获取父窗口的文档,您需要 - 正如此答案所做的那样 - 将其引用为 window.parent.document
【解决方案2】:

您可以尝试在父文档中添加触发函数,然后从 iframe 将其作为常规函数调用。这应该确保您在正确的文档上下文中触发事件。

// In Parent
function triggerComplete () {
  $(document).trigger('complete');
}

// In iFrame
window.parent.triggerComplete();

【讨论】:

    【解决方案3】:

    检查这个解决方案,它非常棘手:

    top.frames['frame_name'].document.getElementById('Processing').style.display = 'none'; 
    

    【讨论】:

      【解决方案4】:

      直接回答OP的问题:因为第一个代码示例中存在错误。

      您将 iframe 的文档对象传递给父级的 $ 函数。这没有多大意义。

      1. Parent 的 jQuery 实例无法在其他窗口的 DOM 对象上触发事件;

      2. 即使可以,它也是 iframe 的文档,但您尝试在父文档上监听事件。

      这可能会起作用:

      window.parent.$(window.parent.document).trigger('complete');
      

      【讨论】:

        猜你喜欢
        • 2011-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多