简体   繁体   English

函数参数不适用于.classList.add

[英]Function parameters not working with .classList.add

I have created a simple function to remove and add classes but I cannot get it to work, below is the html to test on, it needs to work so that when the mouse enters '.dropdown' then #myDropdown will get a class added to it 'show' and when the mouse leaves then the class will be removed: 我创建了一个简单的函数来删除和添加类,但是我无法使其正常工作,下面是要测试的html,它需要正常工作,以便当鼠标进入'.dropdown'时#myDropdown会将一个类添加到它“显示”,当鼠标离开时,该类将被删除:

 const dropDown = document.querySelector('.dropdown'); const dropDownList = dropDown.querySelector('#myDropdown'); const classToToggle = 'show'; dropDown.addEventListener("mouseenter", toggleClass(dropDownList, classToToggle)); dropDown.addEventListener("mouseleave", toggleClass(dropDownList, classToToggle)); function toggleClass(target, className) { if(target.classList.contains(className)) { target.classList.remove(className); } else { target.classList.add(className); } } 
 <div class="dropdown"> <a href="javascript:void(0)" class="dropbtn" style="outline: none;">Dropdown <i class="fas fa-chevron-down"></i></a> <div id="myDropdown" class="dropdown-content"> <p>Item 1</p> <p>Item 2</p> <p>Item 3</p> <p>Item 4</p> </div> </div> 

The function just isn't adding 'className' to the 'target' even though when I console.log the 'className and 'target' parameters they both seem to have come through okay. 即使当我在console.log中记录“ className”和“ target”参数时,函数似乎都没有在“ target”中添加“ className”。

Thanks 谢谢

addEventListener expects a callback function, not a function call result (which happens in your case). addEventListener需要回调函数,而不是函数调用结果(在您的情况下会发生)。 Wrap your function in another function to fix the issue: 将您的函数包装在另一个函数中以解决此问题:

dropDown.addEventListener("mouseenter", () => toggleClass(dropDownList, classToToggle));
dropDown.addEventListener("mouseleave", () => toggleClass(dropDownList, classToToggle));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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