javascript 绑定到动态创建的 iframe 内的事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11088057/
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
Bind to events inside dynamically created iframe
提问by bububaba
I need to bind to an event (say a click
on an arbitrary <input>
) inside an iframe that is created dynamically after the user performs a certain action. The code that appends the iframe AND the code inside the iframe is not mine and I cannot change it in any way (this is a CMS admin panel).
我需要在用户执行某个操作后动态创建的 iframe 内绑定到一个事件(比如 aclick
上的任意一个<input>
)。附加 iframe 的代码和 iframe 内的代码不是我的,我无法以任何方式更改它(这是一个 CMS 管理面板)。
How can I listen to the events using jQuery 1.6(again, this is not my choice, I'm stuck with it). I thought delegate()
might be what I want:
我如何使用jQuery 1.6监听事件(同样,这不是我的选择,我坚持使用它)。我想delegate()
可能是我想要的:
$('body').delegate('iframe input', 'click', function(e) {
alert('bingo?');
});
But the above does not alert when an input is clicked. The below, however, works as expected:
但是当点击输入时,上面不会发出警报。但是,以下内容按预期工作:
$('body').delegate('input', 'click', function(e) {
alert('bingo?');
});
But this is outside the iframe.
但这是在 iframe 之外。
The src
of iframe
points to the same domain, obviously.
该src
的iframe
指向同一个域,很明显。
Any help or just a prod in the right direction is greatly appreciated.
非常感谢任何帮助或只是在正确方向上的刺激。
回答by Prasenjit Kumar Nag
This 'iframe input'
does not selects input
elements inside the iframe
.
此'iframe input'
不选择input
内部元件iframe
。
You can bind the event like
您可以像这样绑定事件
$('body iframe').contents().find('input').bind('click',function(e) {
alert('bingo?');
});
I think You can also use something like
我认为你也可以使用类似的东西
$('body iframe').contents().find('body').delegate('input','click',function(e) {
alert('bingo?');
});
To detect if the iframe has been fully loaded, use the method described in this answer https://stackoverflow.com/a/5788723/344304
要检测 iframe 是否已完全加载,请使用此答案中描述的方法 https://stackoverflow.com/a/5788723/344304
Add In the main/parent document:
在主/父文档中添加:
function iframeLoaded() {
$('body iframe').contents().find('input').bind('click',function(e) {
alert('bingo?');
});
}
Add In the iframe document:
在 iframe 文档中添加:
window.onload = function() {
parent.iframeLoaded();
}
Or use
或使用
$('body iframe').load(function(){
$('body iframe').contents().find('input').bind('click',function(e) {
alert('bingo?');
});
});