我试图设置一个对象,当我创建该对象的实例时,id喜欢将EventListener添加到特定对象。但它引发了一个例外陈述
Uncaught TypeError: Object #<HTMLDivElement> has no method 'nextSlide'
我有以下代码
//Constructor function
function CinnamonSlider (sliderID) {
// Settings - must be set.
this.sliderID = sliderID;
var nextController = document.querySelector('.'+this.sliderID+'-next');
nextController.addEventListener("click", function(e) {
this.nextSlide();
e.preventDefault();
});
}
CinnamonSlider.prototype.nextSlide = function() {
console.log('next');
};
var mySlider = new CinnamonSlider('my-slider');
我在这里做错了什么?
谢谢!
答案 0 :(得分:2)
this
是元素,而不是类。将this
的值存储在变量
function CinnamonSlider (sliderID) {
this.sliderID = sliderID;
var nextController = document.querySelector('.'+this.sliderID+'-next');
var self = this;
nextController.addEventListener("click", function(e) {
self.nextSlide();
e.preventDefault();
});
}
CinnamonSlider.prototype.nextSlide = function() {
console.log('next');
};
var mySlider = new CinnamonSlider('my-slider');