在这里学习Javascript。我用前一个按钮制作了一个小图像轮播。它主要是有效的,但有时我必须点击它两次才能实际改变。任何有关它为什么这样做以及如何解决它的见解?
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);
由于
答案 0 :(得分:0)
changeImage
功能的顺序相反;在设置之前更新值:
function changeImage() {
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
myImage.setAttribute("src", imageArray[imageIndex]);
}