【问题标题】:Is there a way to show the last picture on this slideshow using Javascript?有没有办法使用 Javascript 显示此幻灯片上的最后一张图片?
【发布时间】:2020-08-15 11:31:32
【问题描述】:

到目前为止,我的代码循环了 3/4 或 2/3 个项目。这些项目在一个数组中。最后一张图片说:“未捕获的TypeError:无法读取未定义的属性'classList' 在 HTMLElement”。 显示图片和关闭图片有两个类:分别为“on”和“off”。 HTML 代码:


            <div class="first off">
                <img src="https://c.tadst.com/gfx/750w/sunrise-sunset-sun-calculator.jpg?1" alt=""/>
            </div>

            <div class="second off">
                <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSvLhLs2n6RpRIksOmhqH40yt88fgGcAC6uGlWENi3_WGWfXeoa&usqp=CAU" alt=""/>
            </div>

            <div class="thrird off">
                <img src="https://images.unsplash.com/photo-1512149448423-de868c37fbab?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt=""/>
            </div>

            <div class="last off">
                <img src="https://c.tadst.com/gfx/750w/sunrise-sunset-sun-calculator.jpg?1" alt="">
            </div>
        </section>

Javascript 代码:

var index = 0

arrow.addEventListener("click", ()=>{
    var divs = document.querySelectorAll("div");
    var slide = divs[index]
    index++

    if (index >= divs.length) {
        index = 0
        for (let i = 0; i <= divs.length; i++) {
            divs[i].classList.replace("on", "off")
        }
    }

    slide.classList.replace("off", "on")
    log(index + slide)
})

注意:我确实看过一些类似于这个问题的问题(?),但它们是在 JQuery 中

感谢您的帮助!

【问题讨论】:

  • 如果你能把这个和相关的css(jsfiddle.net)放在一起,人们会很容易帮助你
  • -1 添加到&lt;= divs-length 或使用forEach 迭代您的divs

标签: javascript html arrays loops


【解决方案1】:

我只需要添加另一个检查器,它工作正常

    var slide = divs[index]
    index++

    if (index >= divs.length) {
        index = 0
        for (let i = 0; i < divs.length; i++) {
            divs[i].classList.replace("on", "off")
        }
    }
    //this was needed
    for (let i = 0; i < divs.length; i++) {
        divs[i].classList.replace("on", "off")
    }
    //
    slide.classList.replace("off", "on")

    log(index + slide)

感谢回复的人!

【讨论】:

    【解决方案2】:

    错误说,它正在尝试读取未定义的属性。 undefined 告诉您它正在寻找不存在的东西。

    由于影响到最后一张图片,所以可以假设循环通过数组运行的次数是1。

    array.length 为您提供数组中的元素数量。 但是您正在使用 div[i] 中的数组索引。因为数组的第一个元素由索引 0 寻址,所以 for 循环的运行时间必须比数组中元素的数量少一倍。

    所以在 for 循环中,它必须是 i

    【讨论】:

      【解决方案3】:

      由于数组索引从零开始,您的for 循环应该是:

      for (let i = 0; i < divs.length; i++) {
          ...
      }
      

      【讨论】:

      • 这解决了您的问题吗?这似乎是导致错误的行,但您可能遇到其他问题。
      • 它可以,我已经尝试过了,但是当它从头开始重新启动时,一张图片与另一张重叠。
      猜你喜欢
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 2017-11-02
      • 2022-08-22
      • 1970-01-01
      • 2018-11-09
      • 2020-06-30
      • 1970-01-01
      相关资源
      最近更新 更多