【问题标题】:undefined variable when using setInterval使用 setInterval 时未定义的变量
【发布时间】:2015-04-10 23:10:28
【问题描述】:

我正在尝试建立一个具有每五秒切换一次图像的背景的网站。我使用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 发布到这个文件,但如果我的生活依赖它,我不知道该怎么做。

【问题讨论】:

  • 您的代码从不将imageCount 设置为一个值,所以它是undefined
  • 你设置 imageCount 0 当它等于 2...但它永远不会变成 2...
  • 初始化 var imageCount = 0;
  • 将 var imageCount 移到 setInterval 之上。
  • @Strixy 这不是必需的,因为 JavaScript 会隐式执行此操作。

标签: javascript html scope setinterval


【解决方案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);

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 2015-12-08
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多