2012-05-28 38 views
0

我试图在JavaScript中编写自己的幻灯片。我已经是在Opera,Safari和Chrome浏览器的一个骨架:JavaScript中奇怪的算术行为

var slideShow = (function() { 
    var latestGames = document.getElementById('latestGames').getElementsByTagName('li'); 
    var displayedGame = 0; 
    return { 
     init: function() { 
      latestGames[displayedGame].style.display = 'inline'; 
      setInterval(this.update, 3000); 
     }, 
     update: function(gameToDisplay) { 
      console.log("Displayed game: " + displayedGame); 
      latestGames[displayedGame].style.display = 'none'; 
      gameToDisplay = gameToDisplay || (displayedGame === (latestGames.length - 1) ? 0 : ++displayedGame); 
      console.log("Game to display: " + gameToDisplay); 
      console.log('===================='); 
      latestGames[gameToDisplay].style.display = 'inline'; 
      displayedGame = (gameToDisplay == latestGames.length ? 0 : gameToDisplay); 
     } 
    } 
})(); 

,但在Firefox当我登录了gameToDisplay可变我只得到随机数。我看不出错误在哪里。

预先感谢。

+0

你是如何初始化'gameToDisplay'的? –

+0

是一个可选参数。如果它未定义,我用0初始化它(第12行)。 – Tae

+0

您的问题标题对您所面临的问题没有描述性,而且我不太清楚在阅读问题后实际存在的问题。你可以http://jsfiddle.net一个工作演示? –

回答

4

使用下面的代码:

var self = this; // preserve this to be used inside the callback 
setInterval(function() { self.update(); }, 3000) 

通常你没有工作,但有的(Gecko-based)浏览器的参数传递到计时器回调函数。

+0

是的,这会有所帮助。 – Pointy

+1

没错,没有注意到他在使用'this'。 – ThiefMaster

4

Firefox(pre-13)将参数传递给您的间隔处理程序。该参数给出函数调用的“迟到”;换句话说,应该被调用的时间超过了毫秒数。

见黄色预警here

注:此前壁虎13(火狐13.0 /雷鸟13.0),蛤蚧 传递一个额外的参数回调例程,显示的将 “实际迟到”以毫秒为单位的超时。此非标准 参数不再提供。

+0

尖尖的,我发布了MDN的说明,因为我认为它很重要。 –

+0

是的,这很好,谢谢! – Pointy

0

setInterval每3秒调用一次this.update。更新将有一个对象的引用(this),但我不明白它会在gameToDisplay中传递。

要么删除gameToDisplay,因为它看起来是多余的,或者使其成为像displayedGame这样的实例变量,并将其独立于update()进行设置。

在大多数情况下,它将为空,但Firefox显然会传递某种参数。

+1

他很可能会从其他地方调用此函数,并将参数设置为有意义的值。 – ThiefMaster