javascript jQuery 设置 iFrame onLoad 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3518103/
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
jQuery set iFrame onLoad attribute
提问by Keyo
I need to trigger a function when the iframe loads a second time (the user clicks some link in the iframe). When the iframe page changes I can set the window location to the iframe src.
我需要在 iframe 再次加载时触发一个函数(用户单击 iframe 中的某个链接)。当 iframe 页面更改时,我可以将窗口位置设置为 iframe src。
What I thought would be best is to set an onLoad attribute on the iframe element after the first load. I guess I would need the live event to tell when the iframe has been created, since it's dynamic.
我认为最好的是在第一次加载后在 iframe 元素上设置一个 onLoad 属性。我想我需要实时事件来告诉 iframe 何时创建,因为它是动态的。
This is what I had in mind:
这就是我的想法:
$(document).ready(function() {
$('#tenant_login').fancybox({type:'iframe'});
$('#tenant_login').click(function() {
$('#fancybox-frame').attr('onload', function() {
window.location = $('#fancybox-iframe').attr('src');
});
});
});
If it matters the iframe is not cross domain.
如果重要,iframe 不是跨域的。
回答by Stefan Dunn
$("#fancybox-iframe").load(function(){
window.location = $('#fancybox-iframe').attr('src');
});
This will allow you to redirect the parent window when the iframe loads a different page.
这将允许您在 iframe 加载不同页面时重定向父窗口。
回答by Keyo
If you have control of the iframe content, as I did setting a target="_top"attribute on the hyperlink means the browser will open the link in the browser window rather than the iframe.
如果您可以控制 iframe 内容,就像我target="_top"在超链接上设置的属性一样,这意味着浏览器将在浏览器窗口而不是 iframe 中打开链接。
Main document:
主要文件:
<html>
<body>
<h1>The Main Page</h1>
<iframe src="myIframe.html" />
</body>
<html>
Iframe document:
iframe 文档:
<h2>The IFRAME</h2>
<a href="something.html" target="_top" >
This will open in the browser window rather than any iframe it exists in.
</a>
If you can't put target="_top"on the links of the iframe DOM you will need to capture the click events with javascript from the parent DOM.
如果您无法放置target="_top"iframe DOM 的链接,则需要使用来自父 DOM 的 javascript 捕获点击事件。

