从父框架触发iframe内的元素上的事件处理程序 [英] Triggering an event handler on an element inside iframe from parent frame
问题描述
var frame = $('#mainFrame'); // iframe我正在尝试访问
var link = $('a.btn',frame.contents()); //元素被正确找到
link.trigger('click'); // 什么都没发生。
var e = link.data('events'); // e是未定义的。
这是如何做到的。 >
document.getElementById('ifrmMsg')。contentWindow。$('a:first')。trigger('click');
- 演示: http://jsbin.com/aYijiLe/2
- 父母:http://jsbin.com/aYijiLe/2/edit
- iFrame: http://jsbin.com/IrogeBi/1/edit
您还可以使用 postMessage()
为此目的。它也可以工作跨域。然而,iframe中的JS必须在消息
事件中侦听,即您需要控制iframe的来源。
- 演示: http://jsbin.com/ILAsEmE/1
- 家长: http://jsbin.com/ILAsEmE/1/edit
- iframe: http://jsbin.com/uZEQuTa/2/edit
I have a html page. Inside it I use jQuery to attach click event on a link. Then I use iframe to reference this html page from another page. However I could not trigger the event attached on that link with js (when I click the link with the mouse, the event gets triggered with no problem). How can I trigger that event from parent frame? I have tried the following but it does not work:
var frame = $('#mainFrame'); // the iframe I am trying to access
var link = $('a.btn', frame.contents()); // the element is found correctly
link.trigger('click'); // nothing happens.
var e = link.data('events'); // e is undefined.
Here is how you can do it.
document.getElementById('ifrmMsg').contentWindow.$('a:first').trigger('click');
- Demo: http://jsbin.com/aYijiLe/2
- Parent: http://jsbin.com/aYijiLe/2/edit
- iFrame: http://jsbin.com/IrogeBi/1/edit
You can also use postMessage()
for this purpose. It will work cross domain as well. However JS inside the iframe must listen on the message
event, ie, you need to control the source of the iframe.
- Demo: http://jsbin.com/ILAsEmE/1
- Parent: http://jsbin.com/ILAsEmE/1/edit
- iframe: http://jsbin.com/uZEQuTa/2/edit
这篇关于从父框架触发iframe内的元素上的事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!