JavaScript 幻灯片功能问题

JavaScript slideshow with function issue

在我的 html 中通过 onclick 调用了函数 plusSlides。 This 显示了与我正在使用的 html 相似的功能。 class mySlides 包含将为 showSlides 中的每个 n==x 显示的文本。与 link 中的幻灯片示例不同,当我尝试单击 onclick="plusSlides(-1)" 时,我的功能不起作用。例如,当我在 plusSlides(-1) 上单击三次时,aerialMapfedTiless 都被添加,但 roadMap 没有。有人知道为什么吗?

function roadMap() {    
  map.addLayer(Road);
  map.removeLayer(febTiles);

}
function febTiless() {

  map.addLayer(febTiles);
  map.removeLayer(Road);

}

function aerialMap() {

  map.addLayer(Aerial);
  map.removeLayer(febTiles);
  map.removeLayer(Road);
}


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

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

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

  if (n > slides.length) {slideIndex = 1}    
  if (n < 1) {slideIndex = slides.length}
  if(n == 1)
   aerialMap();
  if(n == 2) 
   febTiless();
  if(n == 3)
   roadMap();

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

错误在这部分代码中:

if (n > slides.length) {slideIndex = 1}    
if (n < 1) {slideIndex = slides.length}
if(n == 1)
  aerialMap();
if(n == 2) 
  febTiless();
if(n == 3)
  roadMap();

在前两行中,slideIndex 变量被调整(正确)以循环回到幻灯片编号的有效范围,但后面的 if 条件是仍然基于 n,其中 not 以这种方式调整,因此 n 将为 0(或 4) 在某些情况下,然后 if 条件中的 none 将是 true.

所以这样调整:

var slideIndex;
showSlides(1);

function plusSlides(n) {
  showSlides(slideIndex + n); // avoid assignment here
}

function currentSlide(n) {
  showSlides(n); // avoid assignment here
}

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

  slideIndex = n; // assign only here, at a single place
  // Don't use n anymore, only work with slideIndex
  if (slideIndex > slides.length) {slideIndex = 1}    
  if (slideIndex < 1) {slideIndex = slides.length}
  if(slideIndex == 1)
   aerialMap();
  if(slideIndex == 2) 
   febTiless();
  if(slideIndex == 3)
   roadMap();

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