jQuery:在 setInterval 调用上出现奇怪的错误我的语法错误吗?
我已经尝试解决这个问题有一段时间了,但现在我想我将其发布在这里,看看我是否最终能理解我遇到的 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
的值呢?
I've been trying to figure this out for a while but now thought I would just post it here and see if I can finally understand this issue with setInterval
I am having.
In case this matters, I'm using jQuery 1.4.4 in this document.
Given the following:
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);
}
}
This however results in:
go is not defined
Which is 'correctly' being logged every 1200 ms. So how can I run my function go()
including passing in the values for slideNumber, direction
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
无法从您发布的内容中看出,但我猜测该代码全部位于某个函数内。 “go”函数必须是全局的才能起作用。当您仅传递一个字符串时,解释器会在计时器触发时在全局上下文中评估该字符串。通过使用像我提供的示例中那样的真实函数,您可以在闭包中捕获本地“go”。
Try this:
Can't tell from what you posted, but I'm guessing that that code is all inside some function somewhere. The "go" function would have to be global for that to work. When you pass just a string, the interpreter evaluates that in the global context when the timer fires. By using a real function like in the example I provided, you capture that local "go" in a closure.
尝试:
Try:
试试这个:
Try this: