幻灯片代码在 Javascript 中不起作用

Slideshow code doesn't work in Javascript

我制作了幻灯片。这是 HTML 代码!

<div class="slideshow-container">
    <div class="mySlides fade">
        <img src="img/background.png" style="width:100%">
    </div>
    <div class="mySlides fade">
        <img src="img/background2.png" style="width:100%">
    </div>
    <div class="mySlides fade">
        <img src="img/background3.png" style="width:100%">
    </div>
    <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
    <a class="next" onclick="plusSlides(1)">&#10095;</a>

</div>

这是 javascript 代码

<script>
    var slideIndex = 1;
    showSlides(slideIndex);

    function plusSlides(n) {
        showSlides(slideIndex += n); 
    }

    function showSlides(slideIndex) {
        var i;
        var slides = document.getElementsByClassName("mySlides");

        if (slideIndex > slides.length) { slideIndex = 1; }
        if (slideIndex < 1) { slideIndex = slides.length; }

        for (i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";
        }
        slides[slideIndex - 1].style.display = "block"; 
    }
</script>

但是由于某些未知原因它不能正常工作,请调试并解释为什么这段代码不能工作?

您定义了两次索引变量:slideIndex。一次作为全局变量,然后作为函数参数,只覆盖函数参数值。您可以删除函数参数并增加/减少 plusSlides 函数中的 slideIndex 值。

var slideIndex = 1;
showSlides();

function plusSlides(n) {
  slideIndex += n;
    showSlides(); 
}

function showSlides() {

    var slides = document.getElementsByClassName("mySlides");

    if (slideIndex > slides.length) { slideIndex = 1; }
    if (slideIndex < 1) { slideIndex = slides.length; }

    for (var i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
    }
    slides[slideIndex - 1].style.display = "block"; 
}