使用setInterval时未定义的变量

时间:2015-04-10 23:10:28

标签: javascript html scope 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发布到此文件中,但如果我的生活依赖于它,我不知道该怎么做。

2 个答案:

答案 0 :(得分:1)

如评论所述,您必须初始化您的变量。 您还必须在每次迭代时递增索引,如果只更改背景,则可能不需要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);

答案 1 :(得分:1)

此实现不需要全局变量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);
    }
}
相关问题