通过按钮数组使eventlistener循环

这是我的HTML和Javascript代码,基本上,如您目前所看到的那样,单击按钮时显示/隐藏3张图像。 事实是,还有另外两行与此类似,我需要知道如何更改javascript代码以使show / hide东西对所有它们都起作用。 我知道它与循环遍历按钮数组有关,但是我不了解Javascript。 这里是 :

<style>
    .show-tapas{
        display: none;
    }
    .show-tapas.showing{
        display: block;
    }
</style>
        <div class="row">
            <div class="col-md-12">
                <div class="load-more-button">
                    <a href="#">Tapas</a>
                </div>
            </div>
        </div>
        <div class="row show-tapas">
            <div class="col-md-4 col-sm-6">
                <a href="images/menu_tapas_1_1.jpeg" data-lightbox="image-1"><div class="thumb">   
                    <div class="portfolio-item">  
                        <div class="image">
                            <img src="images/menu_tapas_1_0.jpeg">
                        </div>
                    </div>                 
                </a>
            </div> 
            <div class="col-md-4 col-sm-6">
                <a href="images/menu_tapas_2_1.jpeg" data-lightbox="image-1"><div class="thumb"> 
                    <div class="portfolio-item">
                        <div class="image">
                            <img src="images/menu_tapas_2_0.jpeg">
                        </div>
                    </div></div>
                </a>
            </div>
            <div class="col-md-4 col-sm-6">
                <a href="images/menu_tapas_3_1.jpeg" data-lightbox="image-1"><div class="thumb">
                    <div class="portfolio-item">
                        <div class="image">
                            <img src="images/menu_tapas_3_0.jpeg">
                        </div>
                    </div></div>
                </a>
            </div>
        </div>
<script>
    var a = document.querySelector('.load-more-button');
    var b = document.querySelector('.show-tapas');
    a.addEventListener("click",function(e){
        e.preventDefault
        b.classList.contains("showing") ? b.classList.remove("showing") : b.classList.add("showing");
    })
</script>

非常感谢你!!!

评论
听风吟
听风吟

In this code I only see one row with the class .show-tapas.

Anyway, you should use querySelectorAll to take every matched items.

var button = document.querySelector('.load-more-button');
var tapas = document.querySelectorAll('.show-tapas');
button.addEventListener("click",function(e){
    tapas.forEach(b => $(b).toggle());
})

Pro-tip: If you have JQuery you might consider using $(b).toggle() instead of b.classList.contains("showing") ? b.classList.remove("showing") : b.classList.add("showing");

点赞
评论