gpt4 book ai didi

javascript - 在 Jquery 中加载图像和不良行为

转载 作者:行者123 更新时间:2023-12-02 19:50:19 24 4
gpt4 key购买 nike

我对自制脚本有一点问题,首先我会给你脚本

    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 的值如您所期望的那样,而不是始终是循环完成运行时它们的最后一个值。

关于javascript - 在 Jquery 中加载图像和不良行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9379273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com