完成后序列不重置

时间:2018-10-23 02:28:16

标签: javascript arrays frontend

我正在尝试完成一个“幻灯片显示”功能,可以将其重用于不同的元素。我正在一个div上对其进行测试,该div包含我的HTML文档中的段落文本,分别表示为 container1,container2 container3 。在按钮上的onclick =“”上调用Clicky()。

let slideshow_divs = ["container1", "container2", "container3"];
    for(let i = 1; i < slideshow_divs.length; i++) {
    document.getElementById(slideshow_divs[i]).style.display = "none";
}

let current_view = 0

function clicky() {
    document.getElementById(slideshow_divs[current_view]).style.display = "none";

    current_view = current_view + 1
    document.getElementById(slideshow_divs[current_view]).style.display = "block";
}

在container3之后,将container1和container2设置为display:none;当通过container3并返回container1时,它保持显示:none;因此,该序列最终只能运行一次。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您需要使用取模运算符再次环绕到数组的开头:

current_view = (current_view + 1) % slideshow_divs.length;

为说明起见,这是current_view值在有无模运算符的情况下的变化表:

Without modulo          With modulo
--------------          -----------
      0                      0
      1                      1
      2                      2
      3 (OOB)                0
      4 (OOB)                1
      5 (OOB)                2

没有模数,一旦current_view达到3,您将走出数组边界(OOB)。

答案 1 :(得分:1)

当幻灯片总数达到后,您需要一种方法将current_view的计数重置为0。可以通过对if的{​​{1}}取模或简单的.length来完成:

slideshow_divs
相关问题