jQuery:在 setInterval 调用上出现奇怪的错误我的语法错误吗?

发布于 2024-10-02 10:00:22 字数 718 浏览 1 评论 0原文

我已经尝试解决这个问题有一段时间了,但现在我想我将其发布在这里,看看我是否最终能理解我遇到的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

迷离° 2024-10-09 10:00:22

试试这个:

if ( MS.timer ) { setInterval( function() { go(2,'right'); }, MS.timer); }

无法从您发布的内容中看出,但我猜测该代码全部位于某个函数内。 “go”函数必须是全局的才能起作用。当您仅传递一个字符串时,解释器会在计时器触发时在全局上下文中评估该字符串。通过使用像我提供的示例中那样的真实函数,您可以在闭包中捕获本地“go”。

Try this:

if ( MS.timer ) { setInterval( function() { go(2,'right'); }, MS.timer); }

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.

夏九 2024-10-09 10:00:22

尝试:

setInterval(function() {
   go(2, 'right');
}, MS.timer);

Try:

setInterval(function() {
   go(2, 'right');
}, MS.timer);
°如果伤别离去 2024-10-09 10:00:22

试试这个:

window.setInterval(go, MS.timer, [2, 'right']);

Try this:

window.setInterval(go, MS.timer, [2, 'right']);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文