繁体   English   中英

使用setInterval时未定义的变量

[英]undefined variable when using setInterval

我正在尝试建立一个网站,其背景每五秒钟切换一次图像。 我使用javascript来实现这一点。 经过一番摆弄之后,我偶然发现了一个似乎是范围问题,因为它一直告诉我var imageCount是未定义的。 我是关于javascript和stackoverflow的新手,我感谢我能获得的任何帮助。

HTML

<body>

    <div id="overlay">




    </div>

    <script>




        window.setInterval(execute, 5000);

        var imageCount;

        function execute() {

            console.log("bla");





                if(imageCount == 0){
                    document.body.style.backgroundImage = "url('huis1.jpg')";
                    console.log("huis1");
                }

                else if(imageCount == 1){
                    document.body.style.backgroundImage = "url('huis2.jpg')";
                    console.log("huis2");
                }

                else if(imageCount == 2){
                    document.body.style.backgroundImage = "url('huis3.jpg')";
                    console.log("huis3");
                    imageCount = 0;
                }

                console.log(imageCount);



        }

    </script>

</body>

我也想将CSS发布到此文件,但是如果我的生活依赖它,我将不知道该怎么做。

如评论中所述,您必须初始化变量。 您还必须在每次迭代中增加索引,如果仅更改背景,则可能不需要if

var imageCount = 0; // initialise your index variable

function execute() {
  // increment your index if value is less than 2 otherwise set it to 0
  imageCount = (imageCount >= 2) ? 0 : ++imageCount;
  // concate your image name with the index value
  document.body.style.backgroundImage = "url('huis" + (imageCount + 1)+ ".jpg')";
}

window.setInterval(execute, 5000);

您不需要此实现的全局变量imageCount。
使用闭包可以轻松完成
参见下面的代码:

window.setInterval(execute(), 5000);

function execute() {
    var imageCount = 0;
    return function() {
        console.log("bla");
        if(imageCount == 0){
            document.body.style.backgroundImage = "url('huis1.jpg')";
            console.log("huis1");
            imageCount = 1;
        } else if(imageCount == 1){
            document.body.style.backgroundImage = "url('huis2.jpg')";
            console.log("huis2");
            imageCount = 2;
        } else if(imageCount == 2){
            document.body.style.backgroundImage = "url('huis3.jpg')";
            console.log("huis3");
            imageCount = 0;
        }
        console.log(imageCount);
    }
}

暂无
暂无

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

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