简体   繁体   中英

opening multiple modals with one function

I have pictures with "learn more" button underneath. I'm trying to figure out how to write the js with each button showing different modal content.

    var modal = document.getElementsByClassName("myModal");
    var btn = document.getElementById("myBtn");
    var span = document.getElementsByClassName("close")[0];

    btn.onclick = function() {
        modal.style.display = "block";
    }

    span.onclick = function() {
        modal.style.display = "none";
    }

    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    };

html looks like:

<div class="gallery">
    <h3>Bobcats</h3>
<img/>
        <button id="myBtn">Learn More</button>
        <div id="myModal" class="modal">
        <div class="modal-content">
        <span class="close">&times;</span>
        <p>
            </p>
        </div></div>

I have 5 sections that need to be shown. Each additional section looks like the one above. I know the buttons need a unique id and I think setting up the class is where I'm running into trouble.

First of all you can't repeat ID's in a page ... they are unique by definition.

Use classes and loop over the class collection to deal with instances, something like:

 // collection of galleries var galleries = document.getElementsByClassName('gallery'); // iterate galleries collection for (var i = 0; i < galleries.length; i++) { let gal = galleries[i], // specific gallery instance modal = gal.querySelector('.modal'), // modal within this gallery instance learnBtn = gal.querySelector('.learn');//button within this gallery instance let toggleModal = function(){ modal.classList.toggle('show'); }; learnBtn.onclick = modal.onclick = toggleModal; } 
 .modal { display: none; } .modal.show { display: block; background: #eaeaea; position: absolute; top: 0; left: 0; right: 0; bottom: 0 } .modal-content { background: white; border: 3px solid #ccc; margin: 20%; padding:30px; } 
 <div class="gallery"> <h3>Gallery 1</h3> <button class="learn">Learn More</button> <div class="modal"> <div class="modal-content"> <span class="close">&times;</span> <p>Gallery 1 modal </p> </div> </div> </div> <div class="gallery"> <h3>Gallery 2</h3> <button class="learn">Learn More</button> <div class="modal"> <div class="modal-content"> <span class="close">&times;</span> <p>Gallery 2 modal </p> </div> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM