简体   繁体   中英

Previous button in Javascript is not working

I want to create a slider in Javascript with two buttons 'Next' and 'Previous'. The next button is working but Previous is not. Here is my code:

 let myImage = document.getElementById('mainImage'); let images = ["./img/th01.jpg", "./img/th02.jpg", "./img/th03.jpg", "./img/th04.jpg", "./img/th05.jpg"]; let imageIndex = 1; function next(){ myImage.setAttribute('src', images[imageIndex]); imageIndex++; if (imageIndex >= images.length) { imageIndex = 0; } } function previous(){ myImage.setAttribute('src', images[imageIndex]); imageIndex--; if (imageIndex <= 0) { imageIndex = images[imageIndex]; } }
 <div id="wrapper"> <img src="./img/th01.jpg" id="mainImage"> <br> <br> <button onclick="previous()">Previous</button> <button onclick="next()">Next</button> </div>

Any help please?

Your next button isn't exactly working either. The problem in both functions is that you're changing the index after changing the src , so the new src will reflect what imageIndex was after the last button click, not the click that just occurred. (and since imageIndex is hard-coded to start at 1, the first click always looks to do what the "Next" button is supposed to do)

Initialize imageIndex to 0, and change it before setting the src .

Also, don't use inline handlers , they have a demented scope chain, require global pollution, and have quote escaping issues. Use addEventListener instead:

 let myImage = document.getElementById('mainImage'); let images = ["./img/th01.jpg", "./img/th02.jpg", "./img/th03.jpg", "./img/th04.jpg", "./img/th05.jpg"]; let imageIndex = 0; const [prev, next] = document.querySelectorAll('button'); next.addEventListener('click', () => { imageIndex++; if (imageIndex === images.length) { imageIndex = 0; } myImage.src = images[imageIndex]; }); prev.addEventListener('click', () => { imageIndex--; if (imageIndex === -1) { imageIndex = images.length - 1; } myImage.src = images[imageIndex]; });
 <div id="wrapper"> <img src="./img/th01.jpg" id="mainImage"> <br> <br> <button>Previous</button> <button>Next</button> </div>

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