简体   繁体   English

JavaScript中奇怪的算术行为

[英]Weird arithmetical behavior in JavaScript

I'm trying to code my own slide show in JavaScript. 我正在尝试用JavaScript编写自己的幻灯片。 What I already have is a skeleton which works in Opera, Safari and Chrome: 我已经有了一个可以在Opera,Safari和Chrome中运行的框架:

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);
        }
    }
})();

But in Firefox I only get random numbers when I log the gameToDisplay variable. 但是在Firefox中,当我登录gameToDisplay变量时,我只会得到随机数。 I can't see where is the error. 我看不到错误在哪里。

Thanks beforehand. 预先感谢。

Firefox (pre-13) passes a parameter to your interval handler. Firefox(13之前的版本)将参数传递给间隔处理程序。 The parameter gives the "lateness" of the function call; 该参数给出了函数调用的“延迟时间”; the number of milliseconds beyond when it should have been called, in other words. 换句话说,超出应调用的毫秒数。

See the yellow warning here : 请在此处查看黄色警告:

Note: Prior to Gecko 13 (Firefox 13.0 / Thunderbird 13.0) , Gecko passed an extra parameter to the callback routine, indicating the "actual lateness" of the timeout in milliseconds. 注意:在Gecko 13(Firefox 13.0 / Thunderbird 13.0)之前,Gecko向回调例程传递了一个额外的参数,指示超时的“实际延迟”以毫秒为单位。 This non-standard parameter is no longer provided. 不再提供此非标准参数。

Use the following code: 使用以下代码:

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

Usually what you did would work, but some ( Gecko-based ) browsers pass an argument to the timer callback function. 通常,您所做的工作会起作用,但是某些( 基于Gecko的 )浏览器会将参数传递给计时器回调函数。

setInterval calls this.update every 3 seconds. setInterval每3秒调用一次this.update。 update will have a reference (this) to the object, but I don't see how it would pass in gameToDisplay. 更新将对此对象有一个引用(此),但我看不到它将如何在gameToDisplay中传递。

Either remove gameToDisplay as it appears to be redundant, or make it an instance variable like displayedGame and set it independently of update(). 删除gameToDisplay,因为它似乎是多余的,或者使其成为诸如displayGame的实例变量,并独立于update()对其进行设置。

In most cases, it will be null, but Firefox obviously passes a parameter of some sort. 在大多数情况下,它将为null,但是Firefox显然会传递某种参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM