首页 > 解决方案 > 为什么我的 JS 代码在调用 JS 函数 showSlides(SLIDEINDEX) 时没有显示任何其他幻灯片;即使我改变了 SLIDEINDEX 的值?

问题描述

我不知道我的 js 代码有什么问题,请检查下面并帮助我通过更改 SLIDEINDEX 的值来显示其他特定幻灯片

    // initialize slideindex with 0 as you want to show the first slide first
var SLIDEINDEX = 3;

showSlides(SLIDEINDEX);

// creating function for showing slides
function showSlides(index){
    // lets select all the slides and dots using querySelectorAll method
    var slides = document.querySelectorAll(".slide");
    var dots = document.querySelectorAll(".dots-navigation");
    // if slide index value is greater than length of slides then jump to 1st slide
    if (index >= slides.length) {SLIDEINDEX = 0;}
    // if we want to jump at the last of the slide incase the user is at the first one
    if (index < 0) {SLIDEINDEX = slides.length - 1;}

    // before showing slides we must hide all the slides and remove active-dots class using for loop
    for (var i = 0; i < slides.length; i++){
        // hide slide elements
        slides[i].style.display = "none";
        // hide dots active-dot class
        dots[i].classList.remove("active-dot");
    }
    // show the slide we want and set the dot class active-dot
    slides[SLIDEINDEX].style.display = "block";
    dots[SLIDEINDEX].classList.add("active-dot");

};

这里是 HTML 和 CSS 代码等其他部分,请点击链接 HTML 代码链接:- https://pastebin.com/nUcqnXnj和 CSS 代码链接:- https://pastebin.com/T2CZPNeh

标签: javascripthtmlcss

解决方案


我认为 SLIDEINDEX var 未使用。仅当它超出幻灯片限制时才设置它。

...
// if slide index value is greater than length of slides then jump to 1st slide
if (index >= slides.length) {SLIDEINDEX = 0;}
// if we want to jump at the last of the slide incase the user is at the first one
else if (index < 0) {SLIDEINDEX = slides.length - 1;}
// else set SLIDEINDEX with new index
else {SLIDEINDEX = index;}
...

推荐阅读