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
Triggering an event handler on an element inside iframe from parent frame
提问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');
- Demo:http://jsbin.com/aYijiLe/2
- Parent: http://jsbin.com/aYijiLe/2/edit
- iFrame: http://jsbin.com/IrogeBi/1/edit
- 演示:http : //jsbin.com/aYijiLe/2
- 家长: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-domainas well. However JS inside the iframe must listen to the message
event, i.e. you need to control the source of the iframe.
您也可以postMessage()
用于此目的。它也可以跨域工作。但是iframe里面的JS必须监听message
事件,即你需要控制iframe的来源。
- Demo: http://jsbin.com/ILAsEmE/1
- Parent: http://jsbin.com/ILAsEmE/1/edit
- iframe: http://jsbin.com/uZEQuTa/2/edit
回答by Dogwood LX
Just place onload() event inside the iframe tag.
只需将 onload() 事件放在 iframe 标签内。
<iframe src="http://myURL.com" onload="myFunction()">