简体   繁体   中英

onclick event for span tag inside div

I'm trying to make a button that opens a image on my webpage and then when you press the x in the corner it closes. I got the image to open, but the close button isn't working and I don't know why.

 var modal = document.getElementById("myModal"); var img = document.getElementById("myImg"); var modalImg = document.getElementById("img01"); img.onclick = function() { modal.style.display = "block"; modalImg.src = "image link"; } function close(i) { document.getElementById(i).style.display = "none"; }
 <div class="sidebar"> <div class="schedule"> <button id="myImg"> <h4><span class="fa fa-caret-right"></span> Schedule</h4> <div id="myModal" class="modal"> <span class="close" style="z-index: 999;" onclick="close('myModal')">&times;</span> <img class="modal-content" id="img01" /> </div> </button> </div> </div>

You have a button inside a modal which is inside a button. That is a problem since the outer button prevents the inner button from working. Lets break those out a bit, and use a relative reference to close the modal.

First separate the modal from the button.

 var modal = document.getElementById("myModal"); var img = document.getElementById("myImg"); var modalImg = document.getElementById("img01"); img.onclick = function() { modal.style.display = "block"; modalImg.src = "https://picsum.photos/200/300"; } function closeModal(el) { el.closest('.modal').style.display = "none"; }
 #myModal { display: none; } .close { display: inline-block; padding: 5px; cursor: pointer; }
 <div id="myModal" class="modal"> <span class="close" style="z-index: 999;" onclick="closeModal(this)">&times;</span> <img class="modal-content" id="img01" /> </div> <div class="sidebar"> <div class="schedule"> <button id="myImg"> <h4><span class="fa fa-caret-right"></span> Schedule</h4></button> </div> </div>

Using relative references like that are handy when you have more than one element that can call them. Additionally it frees you from having to call an ID.

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