如何检测 iframe 是否已加载? [英] How can I detect whether an iframe is loaded?
本文介绍了如何检测 iframe 是否已加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在用户单击按钮后检查 iframe 是否已加载.
I am trying to check whether an iframe has loaded after the user clicks a button.
我有
$('#MainPopupIframe').load(function(){
console.log('load the iframe')
//the console won't show anything even if the iframe is loaded.
})
HTML
<button id='click'>click me</button>
//the iframe is created after the user clicks the button.
<iframe id='MainPopupIframe' src='http://...' />...</iframe>
有什么建议吗?
顺便说一下,我的 iframe 是动态创建的.它不会随着初始页面加载而加载.
By the way, my iframe is created dynamically. It doesn’t load with the initial page load.
推荐答案
你可以试试这个(使用 jQuery
)
You may try this (using jQuery
)
$(function(){
$('#MainPopupIframe').load(function(){
$(this).show();
console.log('iframe loaded successfully')
});
$('#click').on('click', function(){
$('#MainPopupIframe').attr('src', 'https://heera.it');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='click'>click me</button>
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
更新:使用普通的javascript
window.onload = function(){
var ifr = document.getElementById('MainPopupIframe');
ifr.onload=function(){
this.style.display='block';
console.log('laod the iframe')
};
var btn = document.getElementById('click');
btn.onclick=function(){
ifr.src='https://heera.it';
};
};
<button id='click'>click me</button>
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
更新:你也可以试试这个(动态 iframe)
Update: Also you can try this (dynamic iframe)
$(function(){
$('#click').on('click', function(){
var ifr = $('<iframe/>', {
id:'MainPopupIframe',
src:'https://heera.it',
style:'display:none;width:320px;height:400px',
load:function(){
$(this).show();
alert('iframe loaded !');
}
});
$('body').append(ifr);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='click'>click me</button><br />
这篇关于如何检测 iframe 是否已加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文