使jQuery脚本在iframe加载时运行一次

Make jQuery script run once when iframe is loading

本文关键字:一次 运行 脚本 jQuery iframe 加载      更新时间:2023-09-26

我如何使我的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);
});

看我的小提琴

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

我已经试过了

我试过使用.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>

当'#foo'开始加载时,你可以使用这个javascript做一些事情:

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。

在iframe中使用$(document).load访问load事件