Javascript 在 iframe 的父窗口中触发事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4601325/
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
Trigger events in iframe's parent window
提问by Vincent
Why is the following not working:
为什么以下不起作用:
//iframe:
window.parent.$(document).trigger('complete');
//parent window:
$(document).bind('complete', function(){
alert('Complete');
});
while the following IS working:
虽然以下是工作:
//iframe:
window.parent.$('body').trigger('complete');
//parent window:
$('body').bind('complete', function(){
alert('Complete');
});
?
?
回答by moribvndvs
The way events are tracked, you can only trigger or receive events on the same document.
事件跟踪的方式,您只能在同一文档上触发或接收事件。
try
尝试
window.parent.$(window.parent.document).trigger('complete');
回答by Ken Redler
You might try adding a triggering function in the parent document, then calling it as a regular function from the iframe. This should ensure you're triggering the event in the right document context.
您可以尝试在父文档中添加一个触发函数,然后从 iframe 中将其作为常规函数调用。这应该确保您在正确的文档上下文中触发事件。
// In Parent
function triggerComplete () {
$(document).trigger('complete');
}
// In iFrame
window.parent.triggerComplete();
回答by C-F
Answering directly to OP's question: because there is a bug in the first code example.
直接回答 OP 的问题:因为第一个代码示例中存在错误。
You pass the iframe's document object to the parent's $
function. This does not make much sense.
您将 iframe 的文档对象传递给父级的$
函数。这没有多大意义。
Parent's jQuery instance can not trigger event on DOM object of other window;
Even if it could, it is an iframe's document, but you try to listen for the event on parent's document.
Parent 的 jQuery 实例无法在其他窗口的 DOM 对象上触发事件;
即使可以,它也是 iframe 的文档,但您尝试侦听父文档上的事件。
This would probably work:
这可能会起作用:
window.parent.$(window.parent.document).trigger('complete');
回答by Alexander Todorov
Check this solution, it's very tricky:
检查这个解决方案,它非常棘手:
top.frames['frame_name'].document.getElementById('Processing').style.display = 'none';