简体   繁体   中英

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:

 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.

Thanks

addEventListener expects a callback function, not a function call result (which happens in your case). Wrap your function in another function to fix the issue:

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

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