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

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,因此尚未进行调整,因此n将在某些情况下为0(或4),则if条件都不是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";
}

07-24 16:27