jQuery使脚本等待操作完成

时间:2012-10-07 19:39:04

标签: jquery callback wait appendto

是否有可能让jQuery等到这段代码完成它的工作?

if (hrefs[arrayCounter]) {
    $('<li>').append($('<img>', {
        src: hrefs[arrayCounter]
    }).css({
        "height": windowHeight
    })).appendTo(ul)
}​

在此之后,图像会滚动,我需要在滚动之前计算出的宽度。换句话说,当图像仍在加载时,它太快了。据我所知,appendTo()不接受回调所以我该怎么办?

2 个答案:

答案 0 :(得分:1)

在使用此代码之前,请注意图像的onload事件存在多个跨浏览器问题They are described in the documentation for jQuery's .load method.

您需要构建一个Deferred对象并根据每个图像的onload函数对其进行管道。

$.when.apply($,$.map(hrefs, function(href) {
    var imgLoad = $.Deferred(),
        $img = $('<img>').css('height',windowHeight);
    ul.append($('<li>').append($img));
    $img.load($.proxy(imgLoad.resolve,imgLoad));
    $img.attr('src',href);
    return imgLoad;
})).done(function(){
    // all images are loaded when this executes
})

此代码使用jQuery.map将hrefs数组转换为Deferred对象数组。在循环和附加图像时,每个图像都有自己的Deferred对象,其.resolve方法绑定到图像上的.load处理程序。加载图像时,Deferred将解析。

这个Deferreds数组作为参数应用于jQuery.when,它返回一个Promise,它在所有参数解析时解析 - 在这种情况下意味着所有图像都已加载!然后,我们将.done回调附加到该Promise。

答案 1 :(得分:0)

我制作了this jsFiddle,基本上坚持使用图像的.load()事件来激活新代码。这仅适用于loadable content,但我理解的内容似乎符合您的需求。

基本上,您必须将要触发的代码绑定到图像的.on('load',handler)事件。

希望这会有所帮助。

相关问题