2010-11-16 24 views
2

我一直在試圖弄清楚這一點,但現在想我會在這裏發佈,看看我是否可以最終與我setInterval瞭解這個問題。jQuery:在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的值?

回答

3

試試這個:

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

無法從你貼什麼說的,但我猜測,該代碼是所有裏面的一些功能的地方。 「去」功能必須在全球範圍內才能發揮作用。當你傳遞一個字符串時,解釋器會在定時器觸發時在全局上下文中進行評估。通過使用像我提供的示例中的實際函數,您可以捕獲該閉包中的本地「去」。

+0

謝謝,這確實起作用。 – Jannis 2010-11-16 21:53:15

0

嘗試:

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

試試這個:

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

我認爲這是一個Firefox的事情,即使如此,我認爲參數是單獨傳遞,而不是在一個單一的數組。 – Pointy 2010-11-16 20:56:02

+0

你說得對。這在IE中不起作用。 – 2010-11-16 20:58:55