jQuery 从父框架在 iframe 内的元素上触发事件处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12032074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:13:17  来源:igfitidea点击:

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

jqueryiframeevent-handling

提问by YANG Lei

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:

我有一个 html 页面。在它里面,我使用 jQuery 在链接上附加点击事件。然后我使用 iframe 从另一个页面引用这个 html 页面。但是,我无法使用 js 触发该链接上附加的事件(当我用鼠标单击该链接时,该事件被毫无问题地触发)。如何从父框架触发该事件?我已经尝试了以下但它不起作用:

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. 

回答by Aamir Afridi

Here is how you can do it.

这是您如何做到的。

document.getElementById('ifrmMsg').contentWindow.$('a:first').trigger('click');

You can also use postMessage()for this purpose. It will work cross-domainas well. However JS inside the iframe must listen to the messageevent, i.e. you need to control the source of the iframe.

您也可以postMessage()用于此目的。它也可以跨域工作。但是iframe里面的JS必须监听message事件,即你需要控制iframe的来源。

回答by Dogwood LX

Just place onload() event inside the iframe tag.

只需将 onload() 事件放在 iframe 标签内。

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