0

几周前发现了这个网站,这是一个检查我们各种代码并学到很多东西的好地方!

我刚刚开始学习网络编程课程并且遇到了一些问题,我想我的知识。

目标:页面加载后,显示图片andy_black.jpg。两秒钟后,将图像源以及浏览器中的图像更改为名为 andy_white.jpg 的第二个图像。这将每 2 秒来回更改一次。

我查看了这篇文章: SetInterval 函数调用

(我也搜索了其他标签,使用标签 [javascript] [function] 和单词“setinterval”,但大多数都使用 jQuery,我的意图不是使用任何 jQuery,毕竟这是 JavaScript 的实验)。

这在我阅读之前很有帮助,我的代码更长,并且在 setInterval() 函数中没有调用该函数。

所以这里有一些代码: 建议?谢谢大家,喜欢:)

 <img id="img_to_flip" src="pic_src"
        height="100"
        width="100"
         />

            <script type="text/javascript">
                var i = 1;

                function change_pic() {
                    i + 1;
                    if (i == 5) {
                        i = 1;
                    }
                    //I suspect the computer will read i as 5 for some
                    //tiny amount of time before reverting back to 1
                    //which I suspect could cause a further problem, but
                    //is it the source of the current issue?

                    if (i == 1 || i == 2) {
                        document.getElementById('img_to_flip').src = "andy_black.jpg";
                    }
                    else {
                        document.getElementById('img_to_flip').src = "andy_white.jpg";
                    }
                }
                var pic_src = setInterval(change_pic, 2000);
    </script>
4

2 回答 2

1

您忘记实际将新值重新分配给i.

要么使用:

i = i + 1;

或者

++i;

另外,当你只有两个状态时,为什么要数到五呢?具有自动重置计数器的常见范例是使用运算:

i = (i + 1) % 2;

这保证了i永远只有0or的值1

FWIW,这是编写适用于任意数量图像的整个功能的另一种方法 - 只需填充pics数组:

(function() {     // function expression closure to contain variables
    var i = 0;
    var pics = [ "andy_white.jpg", "andy_black.jpg" ];
    var el = document.getElementById('img_to_flip');  // el doesn't change
    function toggle() {
        el.src = pics[i];           // set the image
        i = (i + 1) % pics.length;  // update the counter
    }
    setInterval(toggle, 2000);
})();             // invoke the function expression
于 2013-08-25T20:39:13.320 回答
0

如果您想避免第一次 setInterval 的延迟,请在 setInterval 之前调用该函数,如最佳答案所示:

(function() {     // function expression closure to contain variables
    var i = 0;
    var pics = [ "andy_white.jpg", "andy_black.jpg" ];
    var el = document.getElementById('img_to_flip');
    function toggle() {
        el.src = pics[i];           // set the image
        i = (i + 1) % pics.length;  // update the counter
    }
    toggle()
    setInterval(toggle, 2000);
})();             // invoke the function expression
于 2021-09-20T18:11:11.243 回答