使脚本等到iframe加载后再运行
我正在处理的网站在iframe上有一个Live Chat插件。 如果没有可用的代理,我正在尝试更改图像。 我的代码在控制台上运行,但网站上没有任何内容。
var LiveChatStatus = $("iframe").contents().find(".agentStatus").html(); if (LiveChatStatus =="Offline"){ $('#liveChat').html(''); }
我试过这个:
$('iframe').ready(function(){ var LiveChatStatus = $("iframe").contents().find(".agentStatus").html(); if (LiveChatStatus =="Offline"){ $('#liveChat').html(''); } });
还有这个:
$(document).ready(function(){ var LiveChatStatus = $("iframe").contents().find(".agentStatus").html(); if (LiveChatStatus =="Offline"){ $('#liveChat').html(''); } });
但都没有奏效
最好的解决方案是在父级中定义一个函数,例如function iframeLoaded(){...}
,然后在iframe中使用:
$(function(){ parent.iframeLoaded(); })
这适用于跨浏览器。
如果您无法更改iframe中的代码,那么最佳解决方案是将load
事件附加到iframe。
$(function(){ $('iframe').on('load', function(){some code here...}); //attach the load event listener before adding the src of the iframe to prevent from the handler to miss the event.. $('iframe').attr('src','http://www.iframe-source.com/'); //add iframe src });
绑定到iframe的load事件的另一种方法是在向iframe添加src标记之前将加载侦听器附加到iframe。
这是一个简单的例子。 这也适用于您无法控制的iframe。
// First add the listener. $("#frame").load(function(){ alert("loaded!"); }); // Then add the src $("#frame").attr({ src:"https://apple.com" })
从Elijah Manor的网站上找到了这个,效果非常好
function iFrameLoaded(id, src) { var deferred = $.Deferred(), iframe = $("").attr({ "id": id, "src": src }); iframe.load(deferred.resolve); iframe.appendTo("body"); deferred.done(function() { console.log("iframe loaded: " + id); }); return deferred.promise(); } $.when(iFrameLoaded("jQuery", "http://jquery.com"), iFrameLoaded("appendTo", "http://appendto.com")).then(function() { console.log("Both iframes loaded"); });