jquery 我必须通过修改图像的src,在数组内部迭代并使用setTimeout显示元素

idfiyjo8  于 2022-11-03  发布在  jQuery
关注(0)|答案(1)|浏览(97)

我要做的是:我在一个嵌套数组中迭代,我正确地访问了这个数组,并且我必须及时地完成它。每隔“x”秒,我必须修改一个现有图像的“src”和“rel”(应用淡入淡出),我试图像示例中那样用for循环迭代,但我总是得到最后一个选项,也就是最后一个数组元素

arr = [abc.png, def.png, ghi.png];
for(let i=0; i<3; i++) {    
  val = arr[i]
  setTimeout(function() {
    $("#example").html("<img src="+val+ "rel=" +val+ "style='width:100%'>");
  }, 1000) }
628mspwn

628mspwn1#

您遇到的问题是在1000秒后,当计时器内的代码运行循环时,循环已经再次触发了计时器。此外,您将始终只在循环结束时设置最后一项。原因是您更改了相同的静态元素。
如果我理解正确的话,您希望每x秒更改一次图像
也许像这样的东西能帮上忙
因此,我们使用计时器来确定何时更改图像(每1秒),并使用自调用函数来重复该过程
JavaScript语言:

let imagesArray = [
    "https://i.picsum.photos/id/1010/200/200.jpg?hmac=030jCT8DyI2wW-CYue7-l9xlHBAGpacaSJ6tYnnka3I", 
    "https://i.picsum.photos/id/373/200/200.jpg?hmac=WAwyn7yIFXuyUxxF4b3ijw7qJfIP7oBXicnozVoLj_o", 
    "https://i.picsum.photos/id/70/200/200.jpg?hmac=hRU7tEHltyLUTf0bCrAWFXlPRXOBTsvCcvL-dIUG2CE"];
let imageIndex = 0;
function setImageFunction(){
    //Get the image from the list of images
    let imageUrl = imagesArray[imageIndex];
    //If we have reached the end set imageCount back to 0
    if(imageIndex == imagesArray.length){
        imageIndex = 0;
    }else
    {
         //otherwise go to next index
        imageIndex++;
    }
    //set the image here
     document.getElementById("example").src = imageUrl;

    //Call the iteself to continue the process
    setTimeout(setImageFunction, 1000);
}
setImageFunction();

HTML语言

<img id="example" src="https://dummyimage.com/640x360/fff/aaa" >

这是小提琴手https://jsfiddle.net/604rvzpg/

相关问题