This question already has answers here:
How to access the correct `this` inside a callback?
                            
                                (11个答案)
                            
                    
                5年前关闭。
        

    

我是javascript / jQuery的新手。

我正在做一个简单的淡入淡出滑块以在页面上使用,并且尝试将尽可能多的东西放入对象中,因此每当我创建对象的新实例时,它就可以立即使用。
设置导航时,我首先执行以下操作:

testimonial = new slider($('.testimonials'), $('.testimonials-nav'));
testimonial.nav.on('click', function (e) {
testimonial.setCurrent($(this).data('dir')); // changes the current slider
testimonial.transition(); // what happens when the 'current' changes
testimonial.setHeight(); //because everything is 'position: absolute', I set the parent div height with js
e.preventDefault();
});


但是那样的话,每次创建滑块的新实例时,我都需要重复所有这些代码,因此我尝试了另一种方法,创建了两个方法:

slider.prototype.init = function () {
    this.numberEls();
    this.setHeight();
    this.activateNav();
};


因此,当我创建一个新实例时,我可以执行以下操作

testimonial = new slider($('.testimonials'), $('.testimonials-nav'));
testimonial.init();


并创建了此方法

slider.prototype.activateNav = function () {
    this.nav.on('click', function (e) {
        this.setCurrent($(this).data('dir'));
        e.preventDefault();
    });
};


但是由于事件处理程序中“ this”关键字的范围,它显然不起作用,如何使“ this.setCurrent”在这种情况下起作用?

总体而言,另一个问题是我要完成的目标的一种好方法吗?请记住,它可能会在网站的其他部分使用,而不仅仅是在个人鉴定中。

如果要问的不是太多,我如何使其自动循环?我知道它涉及setTimeOut()之类的东西,但是我不知道具体如何(我要坦白地说这是一个懒惰的问题,实际上我甚至在问如何之前都没有尝试过,但是因为我在这里= P)

Heres the fiddle

PS。很抱歉,如果我没有说清楚自己,英语不是我的母语,并且我有时会为此感到困扰= P

最佳答案

只需保存对this的引用并在以后使用。

slider.prototype.activateNav = function () {
    var that = this;
    this.nav.on('click', function (e) {
        that.setCurrent($(this).data('dir'));
        e.preventDefault();
    });
};

10-06 04:08
查看更多