模态框点击关闭按钮仅首个生效,其余无法关闭的问题求助
Hey there! Let's break down why your modal close buttons (the × ones) only work for the first modal, and get all of them functioning properly.
The Root Causes in Your Code
Looking at your current JavaScript, there are two key issues:
Only the first close button gets an event listener
You're grabbing the close button withdocument.getElementsByClassName("close")[0]— the[0]means you only select the first element with that class. The other two close buttons never get any click event attached.Broken logic in the click handler
The conditionif (event.target == modal || modal2 || modal3)doesn't do what you think it does. This will always evaluate to true (becausemodal2is an object, which is truthy), and it only ever hides the first modal (modal.style.display = "none"), regardless of which close button you click.
The Fix
Let's rewrite the close button event handling to work for all modals:
1. Attach Click Events to All Close Buttons
Replace your existing close button code with this:
// Get all close buttons on the page const closeButtons = document.getElementsByClassName("close"); // Loop through each button and add a click handler for (let i = 0; i < closeButtons.length; i++) { closeButtons[i].onclick = function() { // Find the closest parent modal container (works for modal, modal2, modal3) const parentModal = this.closest('[class^="modal"]'); // Hide that modal if we found it if (parentModal) { parentModal.style.display = "none"; } }; }
2. (Optional) Clean Up the Outside-Click Handler
Your outside-click logic works, but we can make it more concise:
window.onclick = function(event) { // Check if the clicked element is any of the modal containers if (event.target.matches('.modal, .modal2, .modal3')) { event.target.style.display = "none"; } };
How This Works
- The loop ensures every close button gets its own click handler.
this.closest('[class^="modal"]')finds the nearest parent element whose class starts with "modal" — this automatically targets the correct modal for each close button, no hardcoding needed.- The cleaned-up outside-click handler uses
matches()to check if the clicked element is any of your modal containers, then hides it directly.
After making these changes, clicking the × button on any modal will close it properly, and clicking outside any modal will still work as expected.
内容的提问来源于stack exchange,提问作者Nikolai Mikkelsen

