Triggering an event handler on an element inside iframe from parent frame

让人想犯罪 __ 提交于 2019-11-30 08:22:40

问题


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. 

回答1:


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



回答2:


Just place onload() event inside the iframe tag.

<iframe src="http://myURL.com" onload="myFunction()">


来源:https://stackoverflow.com/questions/12032074/triggering-an-event-handler-on-an-element-inside-iframe-from-parent-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!