2012-03-26 12 views
1

我鍵入滾動(0,10,200,10); 但是當它運行時,它傳遞字符串「xxpos」或「yypos」,我確實嘗試了它沒有appostraphes,但它只是沒有工作。Javascript參數

scroll = function(xpos,ypos,time,rounds){ 
    var xxpos = xpos*1; 
    var yypos = ypos*1; 
    var rrounds = rounds*1; 
    var ttime = time*1; 
    x = 0; 
    xyz=window.setInterval("scroller('xxpos','yypos','ttime','rrounds')",ttime); 
} 
function scroller(xpos,ypos,time,rounds){ 
    alert(xpos + ypos + time + rounds); 
} 
+0

你給'scroller'函數的字符串作爲參數。另外,* afaik *,變量將不會從範圍'setInterval'中獲得將評估字符串。 – 2012-03-26 20:44:44

+0

什麼是在那裏未申報的'x = 0'和'xyz = ..'? – 2012-03-26 20:44:48

+0

也許'xyz'是另一個範圍的var,他需要停止他的間隔。但這個名字很醜陋。 – 2012-03-26 20:47:58

回答

6

不要使用字符串,使用閉包(匿名函數)。

window.setTimeout(function() { 
    scroller(xxpos, yypos, ttime, rrounds); 
}, ttime); 
2

它應該是這樣的:

xyz=window.setInterval("scroller(" + xxpos + "," + yypos + "... 

否則你只是傳遞一個字符串xxpos,yypos等

+0

非常感謝!這工作!我不敢相信我沒有想到如此明顯的事情! – 2012-03-26 21:14:31

1

你碰巧知道,在你的代碼,每次調用scroll()建立一個計時器?

你的意思是像做一個循環那樣做嗎?然後:

xyz = window.setTimeout(function(){ 
    scroller(xxpos,yypos,ttime,rrounds) 
},ttime); 
1

你應該使用封閉:

... 
xyz = window.setInterval(function() { scroller(xxpos,yypos,ttime,rrounds); }, ttime); 
... 
1

這是因爲該字符串不會成爲變量。

這會工作:

window.setInterval("scroller("+ xxpos + "," + yypos + "," + ttime + "," + rrounds + ")",ttime); 

或者更好:

window.setInterval(function() { scroller(xxpos, yypos, ttime, rrounds); }, ttime);