Javascript轮播让我有时点击两次

时间:2015-04-30 22:33:45

标签: javascript

在这里学习Javascript。我用前一个按钮制作了一个小图像轮播。它主要是有效的,但有时我必须点击它两次才能实际改变。任何有关它为什么这样做以及如何解决它的见解?

documentation sample

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);

由于

1 个答案:

答案 0 :(得分:0)

changeImage功能的顺序相反;在设置之前更新值:

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

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