简体   繁体   中英

How to handle events in JavaScript?

I want to add class to this li with class .nav-link . I am using JS for it, but I don't know why this code is not functioning. Ps: I am new to JavaScript

<script>
        const navLink = document.querySelector('.nav-link');

        navLink.addEventListener("click", reveal);
        
        function reveal(ev) {
            ev.classList.add("open");
        }

</script>

You have to use ev.target to get that element.

<script>
        const navLink = document.querySelector('.nav-link');

        navLink.addEventListener("click", reveal);
        
        function reveal(ev) {
            ev.target.classList.add("open");  // <----------- Fix this line
        }

</script>

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