我对自制脚本有点问题,首先我会给你脚本
var heighti = $(window).height();
var imageLoading = new Array();
$('.fullHeight').css({'height' : heighti});
var now,hour,minute,second,dateNow = new Array(),countImg=0,i=0,countDateNow = 0;countImg=0,countThis=0,countDateNowAj=0;
/* GET THIS HOUR */
now = new Date();
hour = now.getHours();
minute = now.getMinutes();
second = now.getSeconds();
function date(){
//Function to get date
}
function loadImage(){
countThis = 0;
while(countThis < 6){
date();
var imgOn = 'uploads/original/'+dateNow[countDateNowAj]+'.jpg';
console.log(imgOn);
var img = $("<img />").attr('src', imgOn)
.load(function(){
imageLoading[i] = imgOn ;
i++;
})
.error(function(){
console.log('This is the image now : '+imgOn);
imageLoading[i] = 'images/noimage.jpg';
i++;
});
countThis++;
countDateNowAj++;
}
}
setInterval("dateImg()",1000);
setTimeout("loadImage()",0);
setInterval("loadImage()",5000);
所以这是我的函数,一切都正常,但当我想执行imageLoading[i] = imgOn;
时,脚本总是取最后一个值。
这是我所说内容的日志:http://minus.com/mpWvBsXkQ
首先我检查时间
在我检查图像后,谁将被检查
最后,我检查了imageLoading[i] = imgOn;
的名称
我总是得到最后一次,而不是每一秒。
我希望你能理解我的疑问。
在加载和错误处理程序函数中,异步使用外部作用域中的变量(在本例中,作用域将是loadImage函数),但它们将作为循环的一部分同步更改。如果您希望在实际调用处理程序之前保持它们不变,则需要使用闭包:
function loadImage(){
function imageLoader(i, imgOn) {
console.log(imgOn);
var img = $("<img />").attr('src', imgOn)
.load(function(){
imageLoading[i] = imgOn ;
})
.error(function(){
console.log('This is the image now : '+imgOn);
imageLoading[i] = 'images/noimage.jpg';
});
}
for(countThis = 0; countThis < 6; countThis++, countDateNowAj++) {
date();
imageLoader(i++, 'uploads/original/'+dateNow[countDateNowAj]+'.jpg');
}
}
在这种情况下,imageLoader内部函数将成为加载和错误处理程序运行的范围,因此i和imgOn的值正如您所期望的那样,而不是总是循环运行结束时的最后一个值。
像一样在循环外声明imageLoading
var imageLoading = [];