2011-02-23 101 views
2

我在修改可爱的jquery.carousel.js插件以具有自动更换功能。我想用setInterval()来调用一个函数,但是我无法让它玩得很好。从jQuery插件中调用函数

这里是我此刻的代码:

 
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的第一个参数中尝试什么,它都不起作用。所以。你能帮我解决一下setInterval()函数中的autoSwitch()吗?

回答

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); 
    } 
} 

jQuery.proxy确保函数被调用以正确的背景this值)。更多关于这个一般概念在这里:You must remember 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); 
    } 
} 

一个使用封闭结合上下文(参见:Closures are not complicated),这是通常的方式做到这一点。 jQuery.proxy只是在一个控制良好的环境中在幕后进行关闭,以便您知道它不会关闭比您想要的更多的数据。

+0

谢谢!正是我在找的东西。一般的解决方案也很棒,但对于我所做的事情来说不是必需的:-)再次感谢。 – Bojangles 2011-02-23 18:47:38

+0

@JamWaffles:不用担心,很高兴帮助。 – 2011-02-23 18:55:00