如何检测 iframe 是否已加载?

编程入门 行业动态 更新时间:2024-10-26 18:29:44
本文介绍了如何检测 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 是否已加载?

本文发布于:2023-10-24 17:30:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524564.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加载   iframe

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!