This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
                                
                                    (9个答案)
                                
                        
                                在11个月前关闭。
            
                    
我在closeBtn中添加函数时遇到了一些麻烦,因为它返回错误Uncaught TypeError:closeBtn.addEventListener不是函数

我真的不知道为什么其他变量也能正常工作,我不认为这是一个错字错误,我仔细检查了我调用的类名。这是java脚本

   //View Faculty Schedule MODAL SCRIPT//
var modal2 = document.getElementById('view-modal'); //Get Modal Element
var modalBtn = document.getElementById('searchfaculty'); //Button Element
var closeBtn = document.getElementsByClassName('closeBtn'); //Close Button Element
//opening
modalBtn.addEventListener('click', openModal);
//closing
closeBtn.addEventListener();

function openModal() {
    modal2.style.display = "block";
}

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


然后的HTML

<div id="view-modal" class="modal2">
<div class="modal-view">
    <span class="closeBtn">&times;</span>
    <p>sfsdfsdfsdfdf</p>
</div>




提前致谢

最佳答案

它返回数组中的节点列表集合,因此您必须按索引获取。

closeBtn[0].addEventListener(function(){
 });


see how to choose correct selector

关于javascript - 未捕获的TypeError:closeBtn.addEventListener不是script.js:8的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54766876/

10-10 11:06