我想设置我的小滑块作为类,但是我很难将EventListeners设置为滑动和单击。我只是无法将事件绑定到我的方法中。
" click" -> this.slideto(targetslide)上的EventListener只是吐出" this.slideto不是一个函数",显然我会错误地引用对象的方法。?
我非常感谢任何提示为什么这是不起作用的以及如何解决这个问题。
$(document).ready(function(){
mySlider = new teamSlider();
mySlider.initSlider();
});
function teamSlider(){
console.log("teamSlider");
this.slides_amount = 1;
this.current_slide = 1;
this.val_left = 0;
}
teamSlider.prototype = {
constructor: teamSlider,
initSlider:function() {
this.slides_amount = $('.wrap-slide-game').length;
// set size of elements according to slide numbers
$('.slider-holder').css("width", this.slides_amount*100 + "%");
$('.wrap-slide-game').css("width", 100/this.slides_amount + "%");
$('.slider-idf:nth-child(1)').toggleClass("active");
// EVENTLISTENER Swipe
$('.slider-holder').on("swipeleft", this.slideLeft);
$('.slider-holder').on("swiperight", this.slideRight);
// EVENTLISTENER Indicator click
$('.slider-idf').each(function(index){
$(this).on("click",function() {
this.slideTo(index+1)}
);
});
},
slideLeft:function() {
if (this.current_slide < this.slides_amount) {
// set current identifier inactive
$('.slider-idf:nth-child('+this.current_slide+')').toggleClass("active");
// move slides
this.val_left -= 100;
$('.slider-holder').css("left",this.val_left+"%");
this.current_slide ++;
$('.slider-idf:nth-child('+this.current_slide+')').toggleClass("active");
}
},
slideRight:function() {
if (this.current_slide > 1) {
// set current identifier inactive
$('.slider-idf:nth-child('+this.current_slide+')').toggleClass("active");
this.val_left += 100;
// move slides
$('.slider-holder').css("left",this.val_left+"%");
this.current_slide--;
$('.slider-idf:nth-child('+this.current_slide+')').toggleClass("active");
}
},
slideTo:function(targetslide) {
$('.slider-idf:nth-child('+current_slide+')').toggleClass("active");
this.val_left = -(targetslide-1)*100;
$('.slider-holder').css("left",val_left+"%");
this.current_slide = targetslide;
$('.slider-idf:nth-child('+this.current_slide+')').toggleClass("active");
}
}
咖啡休息时间构成奇迹。问题仅仅是我使用的是" this"的关键字来引用当前的对象。
这在原型函数中正常工作,但在EventHandler内部"此"不再引用对象,而是侦听器正在设置的DOM元素。
通过将我的自定义变量设置为我可以使用它在EventHandlers中调用其函数的本体对象。
也许这对某个地方的人很有用。:)
var _this = this;
// EVENTLISTENER Swipe
$('.slider-holder').on("swipeleft", function(){
_this.slideLeft();
});
$('.slider-holder').on("swiperight", function(){
_this.slideRight();
});
// EVENTLISTENER Indicator click
$('.slider-idf').each(function(index){
$(this).on("click",function() {
_this.slideTo(index+1)
});
});