从jQuery插件中调用函数

Boj*_*les 2 jquery jquery-plugins

我正在修改可爱的jquery.carousel.js插件以具有自动切换功能.我想用来setInterval()调用一个函数,但我不能让它玩得很好.

这是我目前的代码:

autoSwitch: function()
{
    if(runAuto)
    {
        $('.next').click();
    }
},
init: function(el, options) {
    if(this.options.auto)
    {
        setInterval("this.('autoSwitch')", this.options.autoTime);
    }
}

这只是一个片段,还有其他的东西,但我已经把重要的东西留在了.我遇到麻烦的是setInterval("this.('autoSwitch')", this.options.autoTime);.无论我在第一个论点中尝试什么setInterval,它都行不通.所以.你能帮我解决一下autoSwitch()这个setInterval()函数的请求吗?

T.J*_*der 5

我想你正在寻找jQuery.proxy:

init: function(el, options) {
    if(this.options.auto)
    {
        // Give `setInterval` a function to call
        setInterval(jQuery.proxy(this.autoSwitch, this)), this.options.autoTime);
    }
}
Run Code Online (Sandbox Code Playgroud)

jQuery.proxy确保使用正确的上下文(this值)调用函数.关于这个一般概念的更多信息:你必须记住this

那是jQuery特有的.如果您想要更通用的解决方案,可以使用闭包:

init: function(el, options) {
    var context = this;    // Remember what `this` is in a variable
    if(this.options.auto)
    {
        // Give `setInterval` a function to call
        setInterval(function() {
            // The function is a closure that has access to
            // `context`, and so we can call it
            context.autoSwitch();
        }, this.options.autoTime);
    }
}
Run Code Online (Sandbox Code Playgroud)

它使用闭包来绑定上下文(请参阅:闭包不复杂),这是执行此操作的常用方法.jQuery.proxy只是在一个控制良好的环境中进行幕后关闭,所以你知道它并没有关闭比你想要的更多的数据.