简体   繁体   English

w3学校使用的幻灯片

[英]slide show used from w3 schools

I have a question regarding a slide show I am building for an assignment.我有一个关于我正在为作业制作的幻灯片放映的问题。 My debugging skills are not the best as I am new to HTML and JS.我的调试技能不是最好的,因为我是 HTML 和 JS 的新手。 My problem comes from getting a typeError from a line in my slideshow JS.我的问题来自从我的幻灯片 JS 中的一行获取 typeError 。 The problem is in this block here:问题出在此块中:

 var slideIndex = 1;
 showSlides(slideIndex);

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

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

 function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  if (n > slides.length) {
    slideIndex = 1
  }
  if (n < 1) {
    slideIndex = slides.length
  }
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slides[slideIndex-1].style.display = "block";
}

The error is:错误是:

Uncaught TypeError: Cannot read property 'style' of 
undefined at showSlides 

referring to this line:参考这一行:

slides[slideIndex-1].style.display = "block";

The line that the error refers to assumes that there will be at least one slide in slides , but there can be no slides at all, and apparently there are no slides when you call your function.错误所指的行假定 slides 中至少有一张slides ,但根本不可能有幻灯片,而且当您调用 function 时显然没有幻灯片。

You can bail out of the function early if there are no slides:如果没有幻灯片,您可以提前退出 function:

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  if (!slides.length) { // ***
    return;             // ***
  }                     // ***
  if (n > slides.length) {
    slideIndex = 1
  }
  if (n < 1) {
    slideIndex = slides.length
  }
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slides[slideIndex-1].style.display = "block";
}

As for why there aren't any slides, my guess would be that you're running this code too soon.至于为什么没有幻灯片,我猜你运行这段代码太快了。 See this question 's answers for reasons you may not be seeing any matching elements.由于您可能看不到任何匹配元素的原因,请参阅此问题的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM