javascript - 让 jQuery 脚本在 iframe 加载时运行一次

标签 javascript jquery html iframe

如何让 jQuery 脚本在 iframe 加载时运行一次?这是我的代码。

我的代码

$(document).ready(function(){

    //setup a counter to keep our place and cache a selection to the letter wrappers
    var counter = 0,
        $chars  = $(".test").children();

    //setup an interval to animate a letter every so often
    setInterval(function () {

        //select the current letter wrapper and animate it
        $chars.eq(counter).effect( "bounce", {times:1}, 500 );

        //increment the counter so we animate the next letter next time around
        counter++;

        //check if the counter still relates to an index of the $chars collection
        if (counter >= $chars.length) {
            counter = 0;
        }
    }, 250);

});

查看我的 fiddle

当加载 id 为 playing_song 的 iframe 时,我需要它运行脚本一次。它可以在任何时候。

我尝试过的。

我尝试过使用.ready,但显然它只会在准备好时显示,而不是在加载时显示。

我想做的是制作一个带有动画的 div 来覆盖静态 div。但它不能动态更改,因为 iframe 可以随时加载。此方法仅在父级已刷新时才有效。

我追求的是什么

我希望代码做的就是在加载 iframe playing_song 时运行一次,这可以随时发生,而且不止一次。

关于如何实现这一目标有什么建议吗?

最佳答案

您应该能够使用纯 JavaScript 来完成此操作。 考虑这个 html:

<div class="test">
    <span>M</span>
    <span>u</span>
    <span>s</span>
    <span>i</span>
    <span>f</span>
    <span>y</span>
</div>

<iframe id="foo" href="https://youtube.com" width="300" height="250"></iframe>

然后您可以使用此 JavaScript 在“#foo”开始加载时执行某些操作:

var frame_to_load = document.getElementById("foo");
frame_to_load.onload = function() {
    // your js here
}

或者使用jquery:

$('#foo').on('load', function() {
    // your js here
});

如果您有权访问 iframe,您还可以在 iframe 的 $(document).load(function(){...}); 中运行 js。

希望这有帮助。

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

相关文章:

javascript - Django 模板 ifequal 语句始终为 true

javascript - useContext 仅适用于无状态功能组件

jquery - 重新提交具有 jQuery 提交功能并返回 False 的表单

Javascript更改字体颜色onclick

css - 从跨度中删除高度而不使用显示 :none?

javascript - 对象没有方法 'indexOf'

javascript - 如何通过javascript使元素鼠标不可点击但可点击?

javascript - HTML5输入类型Color,如何使用javascript更改其值

html - 空格在 CSS 样式表中发挥作用还是只是为了提高可读性?

javascript - 通过 ID 比较 2 个不同的数组并计算差异