我有一个javascript预加载器,它将图像数组加载到我的页面,然后在完成后执行回调函数。
在预加载期间,我想将当前预加载的图像附加到加载框中的HTML页面。这是我目前的代码。当前代码不适用于每个图像,而只显示最后加载的图像的名称。我该怎么做才能修复我的预加载器功能,以便在每个循环中它将正确的名称附加到我的div?
// Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function(callback) {
checklist = this.toArray();
this.each(function() {
$('div.circleText').html('<p>' + this + '</p>');
$('<img>').attr({ src: this }).load(function() {
checklist.remove($(this).attr('src'));
if (checklist.length == 0) { callback(); }
});
});
};
$([
'../img/about/01-inner-small.png',
'../img/about/01-small.png',
'../img/about/blue-gear.png',
'../img/about/orange-gear.png',
'../img/about/slimeGoblin.png',
'../img/about/03-small.png',
'../img/about/slideshow_back.png',
'../img/about/services_octopus.png',
'../img/about/services_pinkblur.png',
'../img/about/services_blur.png',
'../img/about/services_seahorse.png',
'../img/about/services_coral.png',
'../img/about/water3.png',
'../img/about/water2.png',
'../img/about/water1.png',
'../img/about/02-inner.png',
'../img/about/slime-glow.png',
'../img/about/02_longPhoto.png',
'../img/about/photo1.jpg',
'../img/about/orange-gear.png',
'../img/about/blue-gear.png',
'../img/about/01-small.png',
'../img/about/01.png',
'../img/about/slime-transparent.png',
'../img/about/slime.png',
'../img/about/02-small.png',
'../img/about/02.png',
'../img/about/01_head.png',
'../img/about/services_squid.png',
'../img/about/services_crabs.png',
'../img/about/02-small.png'
]).preloadImages(function(){
// $('#loading').transition({ opacity: 0 }, 1000,'in-out',
// function()
// {
// $('#loading').hide();
// })
});
答案 0 :(得分:0)
您的代码工作正常,您只是因为它发生的速度而没有意识到它。替换以下行:
$('div.circleText').html('<p>' + value + '</p>');
有了这个:
setTimeout(function() {
$('div.circleText').html('<p>' + value + '</p>');
}, 1000 + (index * 100));
这将确保您在处理数组时看到每个数组对象。您可以根据需要调整每个可见的时间。
答案 1 :(得分:0)
上述解决方案无法解决问题,只是显示。
正确答案在这里:http://jsfiddle.net/ES8kw/1/
.load()
功能并不好。
.load(function() {
delete checklist[$.inArray($(this).attr('src'),checklist)];
$('#loading').html('<p>' + $(this).attr('src') + '</p>');
var done = 0;
$.each(checklist,function(i){ if(typeof checklist[i] == "undefined") { done++; }})
if (checklist.length == done) {
callback();
}
});
所有这些都需要包含在setTimeout