classList在for循环中无法按预期工作

时间:2020-06-14 07:11:56

标签: javascript addeventlistener

我有一个滑块,可以显示带有滑动滑块的台式机上的旋转滑块, 我销毁了移动设备上的滑块,并希望显示3个不会随显示更多按钮一起旋转的静态幻灯片。

我为除前三个元素之外的所有元素添加了一个名为hidden的类,并添加了一个按钮以在单击时显示更多幻灯片。

现在,当您单击按钮时,我想从所有幻灯片元素中删除隐藏的类,但是它不起作用。

这是HTML:

<div class="icon-slider">

<div class="swiper-container js-icon-slider">

    <div class="swiper-wrapper">

        <div class="swiper-slide">
            <div class="img-wrap">image here</div>
        </div>
        <div class="swiper-slide">
            <div class="img-wrap">image here</div>
        </div>
        <div class="swiper-slide">
            <div class="img-wrap">image here</div>
        </div>
        <div class="swiper-slide">
            <div class="img-wrap">image here</div>
        </div>
        <div class="swiper-slide">
            <div class="img-wrap">image here</div>
        </div>
        <div class="swiper-slide">
            <div class="img-wrap">image here</div>
        </div>

    </div>

</div>

还有我的JS代码:

 var slider = document.querySelector('.icon-slider'),
     slides = slider.querySelectorAll('.swiper-slide'),
     btnMore = '<div class="more-btn-wrap"><button class="wp-block-button__link">View all</button></div>';

    for (let i = 2; i < slides.length; i++) {
        slides[i].classList.add('hidden');
    }

    if (!slider.querySelector(".more-btn-wrap")) {
        slider.innerHTML = slider.innerHTML + btnMore;
    }

    let btn = document.querySelector('.more-btn-wrap');

    btn.addEventListener('click', function () {
        this.remove();

        slides.forEach(slide => slide.classList.remove('hidden'));
    });

当我尝试将这一行放入控制台时,它可以按预期工作,因此我认为addEventListener很有用

slides.forEach(slide => slide.classList.remove('hidden'));

1 个答案:

答案 0 :(得分:-3)

您不需要2个for循环,请在for循环内添加eventlistener,并在addeventlistener内移除第二个for循环,也请删除3并键入0以从0开始循环

    <style type="text/css">

        .slide {
          width: 80px;
          height: 80px;
          background-color: red;
          border: 2px solid blue;
        }
        .hidden {
          opacity: 0.1;
        }

    </style>

    <button class="btn">Button</button>
    <div class="slider">
       <div class="slide">Slide1</div>
       <div class="slide">Slide2</div>
       <div class="slide">Slide3</div>
    </div>

<script>

    let btn = document.querySelector('.btn');
    let slider = document.querySelector('.slider');
    let slides = slider.querySelectorAll('.slide');

    for (let i = 0; i < slides.length; i++) {
        slides[i].classList.add('hidden');
        btn.addEventListener('click', function() {

                slides[i].classList.remove('hidden');

        });
    }

</script>