简体   繁体   English

如何在 JavaScript 的点击事件上添加 css class?

[英]How to add a css class on click event in JavaScript?

I am trying to add a class to a anchor tag when clicked.单击时,我正在尝试将 class 添加到锚标记。 But, I am getting "add" undefined when I try to use e.classList.add('active-link');但是,当我尝试使用e.classList.add('active-link'); I'm trying to use the same method being used here .我正在尝试使用此处使用的相同方法。

const links = document.querySelectorAll('#navbar__list li a');
links.forEach(function(e) {
    // e.addEventListener('scroll', function() {
    //     e.preventDefault();
    //     for (let i = 0; i < links.length; i++) {

    //     }
    // });

    e.addEventListener('click', function(e) {
        // first remove active_link and active-section class from all a and section elements
        links.forEach(function(e) { 
            e.classList.remove('active-link');
            //console.log(`#section${e.id}`);
            //document.querySelector(`#section${e.id}`).classList.remove('active-section');
        })
        // add the active-class to the a element and active-section to the linked section
        e.classList.add('active-link');
       //document.querySelector(`#section${e.id}`).classList.add('active-section');
    })

});

You have the problem because e.addEventListener('click', function(e) ) the e is event Object, you need to replace this:你有问题,因为 e.addEventListener('click', function(e) ) e 是事件 Object,你需要替换这个:

e.classList.add('active-link');
```
By this
```
e.target.classList.add('active-link');
```

Your e variable name is confusing: depending on the scope it could have three different values.您的e变量名称令人困惑:根据 scope 的不同,它可能具有三个不同的值。 Try this:尝试这个:

const links = document.querySelectorAll('#navbar__list li a');
links.forEach(function(link) {
    link.addEventListener('click', function(event) {
        // first remove active_link and active-section class from all a and section elements
        links.forEach(function(l) { 
            l.classList.remove('active-link');
        })
        // add the active-class to the a element and active-section to the linked section
        link.classList.add('active-link');
    })

});

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

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