我已经尝试解决这个问题有一段时间了,但现在我想我应该将其发布在这里,看看我是否能最终通过我遇到的 setInterval
理解这个问题。
如果这很重要,我在本文档中使用 jQuery 1.4.4。
鉴于以下情况:
var MS = {},
MS.timer = 1200; // this both would be user accessible by the plugin
// if the timer option is set then activate slideshow
if ( MS.timer ) { setInterval( "go(2,'right')" , MS.timer); }
// show the slide (as defined by the pass ins)
function go(slideNumber, direction) {
if ( !paused || !running ) {
console.log('run!'+', '+slideNumber+' , '+direction);
}
}
但这会导致:
go is not defined
每 1200 毫秒“正确”记录一次。那么我如何运行我的函数 go()
,包括传入 slideNumber、direction
的值?
最佳答案
试试这个:
if ( MS.timer ) { setInterval( function() { go(2,'right'); }, MS.timer); }
无法从您发布的内容中看出,但我猜测该代码全部位于某个函数内。 “go”函数必须是全局的才能起作用。当您仅传递一个字符串时,解释器会在计时器触发时在全局上下文中评估该字符串。通过使用像我提供的示例中那样的真实函数,您可以在闭包中捕获本地“go”。
关于jQuery:在 setInterval 调用上出现奇怪的错误......我的语法错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4198799/