Javascript滑块:未捕获TypeError:无法设置属性' className'未定义的

时间:2017-08-01 18:00:47

标签: javascript

我对此很陌生,如果有人能够解释,我真的很感激:

为什么我会收到Uncaught TypeError:无法设置属性' className'未定义的代码如下?

require(
["jquery"],
function($) {

    function Slider() {

        this.slides = document.querySelectorAll('#slides .slide');          
        this.currentSlide  = 0;
        this.slideInterval = 0;

    }

    Slider.prototype.startSlider = function( slideDuration ) {
        this.slideInterval = setInterval( this.nextSlide, slideDuration );
    };

    Slider.prototype.nextSlide = function() {

        this.slides[ this.currentSlide ].className = 'slide';
        this.currentSlide = ( this.currentSlide+1 ) % this.slides.length;
        this.slides[ this.currentSlide ].className = 'slide showing';           

    };

    Slider.prototype.goToThis = function() {

    };

    Slider.prototype.goToNext = function() {

    };

    Slider.prototype.goToPrev = function() {

    };

    var slider = new Slider();
    slider.startSlider( 1000 );

});

当我没有Slider()类时,它可以正常工作。

var slides = document.querySelectorAll('#slides .slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,2000);

function nextSlide() {
    slides[currentSlide].className = 'slide';
    currentSlide = (currentSlide+1)%slides.length;
    slides[currentSlide].className = 'slide showing';
}

1 个答案:

答案 0 :(得分:3)

看起来setInterval创建了自己的上下文。尝试:

setInterval( this.nextSlide.bind(this), slideDuration );