本文介绍了如何检测 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='...' />...</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', 'heera.it'); }); }); <script src="ajax.googleapis/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id='click'>click me</button> <iframe style="display:none" id='MainPopupIframe' src='' /></iframe>jsfiddle 演示.
更新:使用普通的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='heera.it'; }; }; <button id='click'>click me</button> <iframe style="display:none" id='MainPopupIframe' src='' /></iframe>jsfiddle 演示.
更新:你也可以试试这个(动态 iframe)
Update: Also you can try this (dynamic iframe)
$(function(){ $('#click').on('click', function(){ var ifr = $('<iframe/>', { id:'MainPopupIframe', src:'heera.it', style:'display:none;width:320px;height:400px', load:function(){ $(this).show(); alert('iframe loaded !'); } }); $('body').append(ifr); }); }); <script src="ajax.googleapis/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id='click'>click me</button><br />jsfiddle 演示.
更多推荐
如何检测 iframe 是否已加载?
发布评论