【问题标题】:Uncaught TypeError: Cannot read property 'style' of undefined for carroussel未捕获的类型错误:无法读取 carroussel 未定义的属性“样式”
【发布时间】:2019-05-22 20:41:41
【问题描述】:

我在第 12 行收到“Uncaught TypeError: Cannot read property 'style' of undefined”我不知道为什么

class Slider {
duration = 0;
currentSlide = 0;
slides = document.getElementsByClassName("slide");
constructor() {
    this.initSlide();  
}

initSlide() {
    var i;
    for (i = 0; i < this.slides.length; i++) {
        this.currentSlide[i].style.display = "none";  
    }
    this.currentSlide++;
    if (this.currentSlide > this.slides.length) {
        this.currentSlide = 1
    }    
    this.slides[this.currentSlide - 1].style.display = "block"; 
    setTimeout(this.initSlide, 3000); 
}    

}

【问题讨论】:

    标签: javascript


    【解决方案1】:

    在您的initSlide-方法中,您尝试迭代具有类名称slide 的元素列表。

    在您的循环中,您使用this.currentSlide 作为一个数组,并且您假设数组元素是一个具有属性样式的html 元素。但是您将属性 currentSlide 声明为数字类型并分配了值 0。您不能迭代 0 或数字类型。

    正确的迭代应该是:

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

    但我认为,这不是你想要的,对,但它解决了你的错误。

    编辑:为避免所有以下错误,您必须先检查页面上是否有幻灯片:

    if(this.slides.length >= 1) {
      this.slides[this.currentSlide - 1].style.display = "block"; 
    }
    

    并使用箭头函数,而不是函数本身,以避免您的内部 this 引用指向窗口对象,而不是指向您生成的对象。

    setTimeout(() => this.initSlide(), 3000);
    

    【讨论】:

    • 是的,谢谢,但现在我在上一行遇到了同样的长度问题,抱歉,我 3 周前才开始学习 javascript,我只是想了解一下。
    • @iceson 为避免所有后续错误和可能出现的错误,请参阅我的编辑。
    • 非常感谢您花时间向我解释。旋转木马正在工作。
    • @iceson 你能把我的答案标记为解决方案吗?或者是另一件事对你有帮助?
    猜你喜欢
    • 1970-01-01
    • 2017-07-11
    • 2020-12-25
    • 2019-07-24
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2015-01-06
    相关资源
    最近更新 更多