如何让IFRAME听取与父级相同的事件(并触发相同的处理程序) [英] How to get IFRAME to listen to same events as parent (and fire the same handlers)

查看:91
本文介绍了如何让IFRAME听取与父级相同的事件(并触发相同的处理程序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有嵌入式IFRAME的HTML页面(父级)。父页面有几个鼠标和键盘事件的事件监听器,如下所示(我正在使用Prototype库)。

I've got an HTML page (the parent) with an embedded IFRAME. The parent page has a couple of event listeners for mouse and keyboard events, as shown below (I'm using the Prototype library).

var IdleMonitor = Class.create({

    active: null,
    initialize: function(ii) {
        Element.observe(window, "mousemove", this.sendActiveSignal.bind(this));
    },

    sendActiveSignal: function() {
        console.log("MOUSE");
    }
});

var idleMonitor = new IdleMonitor();

IFRAME是一个单独的文件,并且不响应父母的事件。所以我在IFRAME中设置了一些代码:

The IFRAME, being a separate document and all, doesn't respond to the parent's events. So I've set up some code in the IFRAME like:

<script type="text/javascript" >

        Element.observe(window, "mousemove", function(p) {
            parent.sendActiveSignal();

        });
</script>

但是这给了我一个错误(sendActiveSignal是一个未定义的函数)。
如何使IFRAME也监听相同的事件并激活父事件的处理程序,最好是以Prototype-y的方式?

But that's giving me an error (sendActiveSignal is an undefined function). How do I make the IFRAME also listen for the same events and fire the parent's event handlers, preferably in a Prototype-y way?

推荐答案

首先,我真的认为在将函数绑定为事件侦听器时应该使用bindAsEventListener。通过这样做,您可以访问事件的参数。您可能稍后需要它。

First of all, I really think you should use bindAsEventListener when binding functions as event listeners. By doing that, you have access to the event's arguments. You may need it later.

在您的情况下,我注意到的第一件事是您的sendActiveSignal被声明为您IdleMonitor类的成员。如果你只是通过parent.sendActiveSignal调用它,JS引擎将找不到它,因为我猜测父节点不是IdleMonitor实例。 (事实并非如此,我现在可以告诉它:])

In your case, the first thing I noticed is that your sendActiveSignal is declared as a member of you IdleMonitor class. The JS engine won't find it if you just call it by parent.sendActiveSignal, since I'm guessing that parent is not a IdleMonitor instance. (And it is not, I can tell it right now :])

在你的iframe中,你必须访问idleMonitor变量,你可以通过引用它来做到这一点这样:

Inside your iframe, you have to access the idleMonitor variable, and you can do that by referencing it this way:

<script type="text/javascript">
Element.observe(window, "mousemove", function(p) { parent.document.idleMonitor.sendActiveSignal(); });
</script>

这几乎应该有效,我现在无法测试。

This pretty much should work, I can't test it right now.

这篇关于如何让IFRAME听取与父级相同的事件(并触发相同的处理程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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