0

我需要在一定的时间间隔(比如说 6 秒)后计算加载到页面中的图像数量,然后需要进行一些处理。所以 6 秒后我调用 scan_images_results ( ) 函数。

function scan_images_results ( ) {
   $.when(count_loaded_image()).then(function() {
    window.console.log("i m here");
    });
}

function count_loaded_image() {
    var counter = 0;
    $('img[id^="picThumbImg_"]').imagesLoaded()
        .progress( function( instance, image ) {
            var result = image.isLoaded ? 'loaded' : 'broken';
            console.log( 'image is ' + result + ' for ' + image.img.src );
        if(image.isLoaded) {
            counter++;
        }

        });

    console.log('counter--'+counter);
}

输出如下。

counter--0
i m here
image is broken for https://myserver/cgi-bin/sf?f=58343d875e7a10290d0464cabfc276e5.jpg
image is broken for https://myserver/cgi-bin/sf?f=68343d875e7a10290d0464cabfc276e6.jpg
image is broken for https://myserver/cgi-bin/sf?f=78343d875e7a10290d0464cabfc276e7.jpg
.........
........ 28 times 

我正在使用“ https://github.com/desandro/imagesloaded ”来检查图像是否已加载。我损坏了 28 张图像,这是正确的计数。但是我的计数器功能稍后会被执行。即我的预期输出是

image is broken for https://myserver/cgi-bin/sf?f=58343d875e7a10290d0464cabfc276e5.jpg
image is broken for https://myserver/cgi-bin/sf?f=68343d875e7a10290d0464cabfc276e6.jpg
image is broken for https://myserver/cgi-bin/sf?f=78343d875e7a10290d0464cabfc276e7.jpg
.........
........ 28 times 
counter--0
I m here

我知道问题出在哪里?我需要按顺序执行该函数,为此我需要创建延迟对象。但我无法解决我的问题。

4

1 回答 1

1

你不需要$.when,你甚至不需要额外的功能。

function scan_images_results() {
    var counter = 0;
    $('img[id^="picThumbImg_"]').imagesLoaded()
        .progress(function (instance, image) {
            var result = image.isLoaded ? 'loaded' : 'broken';
            console.log('image is ' + result + ' for ' + image.img.src);
            if (image.isLoaded) {
                counter++;
            }

        })
        .always(function () {
            console.log("I'm here");
        });

    console.log('counter--' + counter);
}

如果你想保留这个功能,

function scan_images_results() {
    count_loaded_image().always(function () {
        console.log("I'm here");
    });
}

function count_loaded_image() {
    var counter = 0;
    return $('img[id^="picThumbImg_"]').imagesLoaded().progress(function (instance, image) {
        var result = image.isLoaded ? 'loaded' : 'broken';
        console.log('image is ' + result + ' for ' + image.img.src);
        if (image.isLoaded) {
            counter++;
        }
    });
}
于 2013-11-13T19:08:44.810 回答