从父框架触发 iframe 内元素的事件处理程序 [英] Triggering an event handler on an element inside iframe from parent frame
问题描述
我有一个 html 页面.在其中,我使用 jQuery 在链接上附加点击事件.然后我使用 iframe 从另一个页面引用这个 html 页面.但是我无法使用 js 触发附加在该链接上的事件(当我用鼠标单击链接时,事件被触发没有问题).如何从父框架触发该事件?我尝试了以下方法,但它不起作用:
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.
推荐答案
你可以这样做.
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 必须监听message
事件,即你需要控制 iframe 的来源.You can also use
postMessage()
for this purpose. It will work cross-domain as well. However JS inside the iframe must listen to themessage
event, i.e. you need to control the source of the iframe.- 演示:http://jsbin.com/ILAsEmE/1
- 家长:http://jsbin.com/ILAsEmE/1/edit李>
- iframe:http://jsbin.com/uZEQuTa/2/edit李>
这篇关于从父框架触发 iframe 内元素的事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!