简体   繁体   中英

JavaScript won't change image - Slider

I don't understand why my slider won't work.

On the HTML page, I have first time, from the slider, and link to JavaScript. In JavaScript, I have an array that includes 2 images. Unfortunately, my slider doesn't work. The image won't change. It stays on the first one.

What might be wrong?

 var myImage=document.getElementById("slide"); var imageArray=["image1.jpg", "image2.jpg"]; var imageIndex=0; function changeImage () { slider.setAttribute("src", imageArray [imageIndex]); imageIndex++; if (imageIndex>=imageArray.length) { imageIndex=0; } } var intervalHandle = setInterval(changeImage,2000); 
 <!DOCTYPE html> <html lang="cs"> <head></head> <body> <img src="image1.jpg" id="slide"/> <script src="javascript.js"></script> </body> </html> 

try the following code:

var myImage=document.getElementById("slide");

var imageArray=["image1.jpg", "image2.jpg"];

var imageIndex=0;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM