【问题标题】:Jquery $(window).load not working as expected when in script referenced from inside an iframe在从 iframe 内部引用的脚本中,Jquery $(window).load 无法按预期工作
【发布时间】:2013-05-02 15:53:02
【问题描述】:

我有一个带有 iframe 的页面。我正在尝试将动画加载到这个 iframe 中。每条内容都是一个 html 页面,其中包含对执行某种动画的 javascript/jquery 脚本的引用。例如:

content.html

<head>
<link rel="stylesheet" type="text/css" href="css/slide.css">
<script src="js/library/big_slide_img.js"></script>
</head>
<body>
    <img class="big_slide_img" src="http://25.media.tumblr.com/0ab6f805c5a3591168e2fe2133552054/tumblr_mk52iuvbNI1s631nvo1_1280.jpg">
</body>

big_slide_img.js

$(window).load(function()
{
    $("#iframe").contents().find('.big_slide_img').animate({left: '-=521'}, 800,function(){});
});

如何加载

loadSlide = function(slide_no)
    {
        $.ajax(
        {
            url: "http://myurl.com",
            async: false,
            jsonpCallback: 'jsonCallback',
            contentType: "application/json",
            type: "GET",
            dataType: "jsonp",
            data: {"action": "loadall"},
            success: function(data)
            {
                $('#frame_title').html(data.title);
                $('#text').html(data.text);
                $('#iframe').contents().find('html').html(data.animation); 
            },
            error: function (event, jqXHR, ajaxSettings, thrownError)
            {
                alert('[event:' + event + '], [jqXHR:' + jqXHR + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])');
            }
        });
    };

我的问题

动画不一致,我怀疑这是由于 $(window).load 没有按预期等待。延迟解决了我所有的问题:

$(window).load(function()
{
    $("#iframe").contents().find('.big_slide_img').delay(800).animate({left: '521'}, 800,function(){});
});

我怎样才能毫不拖延地做到这一点?由于我不知道这些文件中的代码是什么,我想避免在外部监视 iframe 并在完成后调用特定函数。我希望/假设,我只是没有引用正确的东西。

非常感谢。

【问题讨论】:

标签: javascript jquery iframe onload


【解决方案1】:

jQuery 不会调用“加载”触发器,因为实例化 jQuery 的页面已经加载。

您可以在 iframe 中加载 jquery 并将此代码放入“big_slide_img.js”中: $(function(){ $("#iframe").contents().find('.big_slide_img').delay(800).animate({left: '521'}, 800,function(){}); });

或者你可以在 iframe 之外创建一个触发器,当 iframe 加载时调用它。

还有很多其他方法。

【讨论】:

  • 嗯......除了它确实被调用了。也许它会立即被调用,因为页面已经加载。
【解决方案2】:

根据上面 VictorVRS 的评论和我的回复,我意识到我需要触发 iframe 的加载功能(我认为只有外部页面是)。我的 ajax 调用现在返回一个 url,而不是实际数据,它被设置到 iframe 的 src 中,加载页面。这变成了:

$('#iframe').contents().find('html').html(data.animation); 

这个:

$('iframe').attr('src',data.animation_url);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 2013-09-30
    • 2014-03-27
    相关资源
    最近更新 更多