从iframe触发jQuery事件 [英] Triggering a jQuery event from iframe

查看:94
本文介绍了从iframe触发jQuery事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个场景,我在iframe中发生了一些事件,直到现在一切都运转良好。我刚遇到问题,我想从iframe派遣一个事件给父母。

Here's the scenario, I have events happening from within an iframe and up until now everything is working well. I just ran into the problem where I want to dispatch an event from the iframe to the parent.

我正在使用它从iframe触发事件:

I'm using this to trigger the event from the iframe:

$('body', window.parent.document).trigger('eventName');
//and I've also tried
$(window.parent.document).find('body').trigger('eventName');

然后在父页面中我正在收听这样的事件:

And then in the parent page I've listening for the event like this:

$('body').bind('eventName', myFunction)

我知道脚本到达触发因为我在触发器之前和之后卡住了 console.log 。 iframe在同一个域上,所以没有问题。

I know the script gets to the trigger because I stuck a console.log before and after the trigger. The iframe is on the same domain so there is no problem there.

我可以直接在父页面上调用一个函数: window。 parent.functionName 但我想知道使用基于事件的解决方案是否可行。

I can call a function on the parent page directly like this: window.parent.functionName but I was wondering if this is possible with using using an event based solution.

@cwolves答案效果很好:

@cwolves answer is working great:

parent.$('body').trigger( 'eventName' );


推荐答案

如果您在父框架中加载了jQuery,请尝试:

If you have jQuery loaded in the parent frame, try:

parent.$('body').trigger( 'eventName' );

如果没有,试试这个,我不确定它是否会起作用但我只是看着jQuery源码并认为它​​可能:

If not, try this, I'm not sure if it will work but I just looked at the jQuery source and think it may:

var pBody = $( parent.document.body );
pBody.trigger( 'eventName', pBody.data() );

(绑定 eventName )
据我所知,问题是jQuery正在使用来自本地页面的数据,这导致了问题,因为它看起来正在尝试从其他帧加载数据。换句话说,它是一团糟,但 .bind 中接受了数据参数, .trigger 等。

(And do the same thing when binding eventName) The issue, as far as I can tell, is that jQuery is using the data from the local page, which is causing issues because it looks like it's trying to load data from the other frame. In other words, it's a mess, but there are data params accepted in .bind, .trigger, etc.

这篇关于从iframe触发jQuery事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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