我需要计算一定时间间隔后加载到页面中的图像数量(比如说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张图片,这是正确的计数。但是我的计数器功能正在被执行.i.e。我的预期输出是
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
我知道问题出在哪里?我需要按顺序执行该函数,为此我需要创建延迟对象。但我无法解决我的问题。
答案 0 :(得分: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++;
}
});
}