如何在 JavaScript 的点击事件上添加一个 css 类?

单击时,我试图将一个类添加到锚标记。但是,当我尝试使用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');

    })


});


蝴蝶不菲
浏览 92回答 2
2回答

潇潇雨雨

您遇到问题是因为 e.addEventListener('click', function(e) ) e 是事件对象,您需要替换它:e.classList.add('active-link');```By this```e.target.classList.add('active-link');```

红糖糍粑

您的e变量名称令人困惑:根据范围,它可能具有三个不同的值。尝试这个 :const links = document.querySelectorAll('#navbar__list li a');links.forEach(function(link) {&nbsp; &nbsp; link.addEventListener('click', function(event) {&nbsp; &nbsp; &nbsp; &nbsp; // first remove active_link and active-section class from all a and section elements&nbsp; &nbsp; &nbsp; &nbsp; links.forEach(function(l) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; l.classList.remove('active-link');&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; // add the active-class to the a element and active-section to the linked section&nbsp; &nbsp; &nbsp; &nbsp; link.classList.add('active-link');&nbsp; &nbsp; })});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript