为closeBtn绑定addEventListener时触发TypeError错误求助
Hey there! Let's break down what's going on here and fix that error.
The Root Cause
The problem lies in how you're selecting the close button:
var closeBtn = document.getElementsByClassName('closeBtn');
getElementsByClassName() returns an HTMLCollection—a collection-like object containing all elements that match the class, not a single DOM element. Even if only one element has that class, you can't call addEventListener() directly on the collection because it doesn't have this method built in.
Quick Fixes
Here are two straightforward ways to resolve this:
1. Target the first element in the collection
Since your HTML only has one .closeBtn, you can grab the first item (index 0) from the returned collection:
// Closing closeBtn[0].addEventListener('click', closeModal);
2. Use querySelector() instead
querySelector() returns the first single element that matches the selector, which is exactly what you need here. Replace your closeBtn declaration with:
var closeBtn = document.querySelector('.closeBtn'); // Close Button Element
Then you can use addEventListener() normally:
closeBtn.addEventListener('click', closeModal);
Bonus Fix: Typo in closeModal()
You also have a small typo in your closeModal function—you're referencing modal instead of modal2 (the variable you defined for your modal):
function closeModal() { modal2.style.display = "none"; // Changed from "modal" to "modal2" }
Full Corrected Code
Here's the fixed JavaScript code put together:
//View Faculty Schedule MODAL SCRIPT// var modal2 = document.getElementById('view-modal'); //Get Modal Element var modalBtn = document.getElementById('searchfaculty'); //Button Element var closeBtn = document.querySelector('.closeBtn'); // Close Button Element //opening modalBtn.addEventListener('click', openModal); //closing closeBtn.addEventListener('click', closeModal); function openModal() { modal2.style.display = "block"; } function closeModal() { modal2.style.display = "none"; }
That should get your modal closing properly without errors!
内容的提问来源于stack exchange,提问作者dread

