我想将我的小滑块设置为类,但我很难设置用于滑动和单击的eventlisteners。 我只是不能将事件绑定到我的方法。
event &iste;&#34>点击" - > this.slideTo(targetslide)只是吐出" 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");
}
}
&#13;
答案 0 :(得分:0)
这在原型函数中运行良好但在eventhandler中“this”不再引用该对象,而是设置了侦听器的dom元素。
通过将我的自定义变量_this设置为我的instanced对象,我可以使用它在事件处理程序中调用它的函数。
也许这对某些人有用。 :)
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)
});
});