只是在这里学习Javascript。我使用上一个按钮制作了一个小图像轮播。它通常可以正常工作,但有时我必须单击两次才能使其实际更改。关于它为什么这样做以及如何解决的任何见解?

https://jsfiddle.net/2t79qw4r/6/

var myImage = document.getElementById("mainImage");
var imageArray = ["_images/overlook.jpg", "_images/winery_sign.jpg", "_images/lunch.jpg", "_images/bigSur.jpg", "_images/flag_photo.jpg", "_images/mission_look.jpg"];
var imageIndex = 0;
var prevImage = document.getElementById("prev");

function changeImage() {
  myImage.setAttribute("src", imageArray[imageIndex]);
  imageIndex++;
  if (imageIndex >= imageArray.length) {
    imageIndex = 0;
  }
}

prevImage.onclick = function() {
  if (imageIndex === 0) {
    imageIndex = imageArray.length -1;
  } else {
    imageIndex = imageIndex - 1;
  }
  myImage.setAttribute("src", imageArray[imageIndex]);

};

setInterval(changeImage,3000);


谢谢

最佳答案

changeImage函数的顺序相反。设置之前更新值:

function changeImage() {
    imageIndex++;
    if (imageIndex >= imageArray.length) {
        imageIndex = 0;
    }
    myImage.setAttribute("src", imageArray[imageIndex]);
}


小提琴:https://jsfiddle.net/afptfbs8/

10-06 00:02