jQuery在iframe窗口中触发自定义事件
问题描述:
我无法在父文档的iframe中触发自定义事件.
I'm having trouble triggering a custom event in an iframe from the parent document.
在孩子中,我有这样的代码:
In the child I have code like this:
$(window).on( 'my-event', function() { console.log( "GOT IT" ) } )
在父级中,我获取iframe并尝试发送事件:
In the parent I get the iframe and try to send an event:
iframe = document.getElementById( 'content-frame' )
$(iframe.contentWindow).trigger( 'my-event' )
事件未到.我尝试使用文档"而不是窗口,但还是没有运气.
The event doesn't arrive. I've tried using 'document' instead of window, but still without luck.
可以用jquery完成吗?
Can this be done with jquery?
我希望有一种简单的方法,这样我就可以避免编写调度函数,从而使父级在iframe中调用一个函数并调度事件.
答
这是我的解决方案.在父级中,您可以使用以下命令触发事件:
Here is my solution. In the parent, you can fire the event using the following:
$('#content-frame')[0].contentWindow.$('body').trigger('my-event');
在孩子中,您可以收听事件:
In the child, you can listen for the event:
$('body').on('my-event', function(e) {
alert("Hello, World! Message received!");
});