javascript - 让脚本等到 iframe 加载后再运行

标签 javascript jquery iframe

我工作的网站在 iframe 上有一个在线聊天插件。如果没有可用的代理,我正在尝试更改图像。我的代码在控制台上有效,但在网站上没有任何作用。

var LiveChatStatus = $("iframe").contents().find(".agentStatus").html();
if (LiveChatStatus =="Offline"){
    $('#liveChat').html('<img src="%%GLOBAL_ShopPath%%/product_images/theme_images/liveoffline.png">');
}

我试过这个:

$('iframe').ready(function(){
    var LiveChatStatus = $("iframe").contents().find(".agentStatus").html();
    if (LiveChatStatus =="Offline"){
        $('#liveChat').html('<img src="%%GLOBAL_ShopPath%%/product_images/theme_images/liveoffline.png">');
    }
});

还有这个:

$(document).ready(function(){
   var LiveChatStatus = $("iframe").contents().find(".agentStatus").html();
   if (LiveChatStatus =="Offline"){
       $('#liveChat').html('<img src="%%GLOBAL_ShopPath%%/product_images/theme_images/liveoffline.png">');
   }
});

但是都没有用

最佳答案

最好的解决方案是在您的父级中定义一个函数,例如 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
});

关于javascript - 让脚本等到 iframe 加载后再运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17436881/

相关文章:

javascript - 我如何 for...in 循环遍历这个包含多个 cookie 的 JSON 数组来获取键值对?

javascript - 如何在 EJS 模板中使用 jQuery 和 vanilla JS

javascript - 如何获取iframe的document对象?

html - 为什么自关闭 iframe 标记会阻止显示更多 DOM 元素?

javascript - 将正则表达式与 Javascript 结合使用

javascript - 我如何通过 api 获取大量用户?使用 async wait

jquery - 默认数据表搜索框文本

javascript - 带有 iFrame 的 HTML 编辑器不工作

javascript - Bootstrap 模式正常出现但没有正确显示其中的内容?

jquery - 在模板中的剑道网格单元格中显示下拉菜单