亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 JavaScript 的點擊事件上添加一個 css 類?

如何在 JavaScript 的點擊事件上添加一個 css 類?

蝴蝶不菲 2022-11-27 16:21:01
單擊時,我試圖將一個類添加到錨標記。但是,當我嘗試使用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');    })});
查看完整描述

2 回答

?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

您遇到問題是因為 e.addEventListener('click', function(e) ) e 是事件對象,您需要替換它:


e.classList.add('active-link');

```

By this

```

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

```


查看完整回答
反對 回復 2022-11-27
?
紅糖糍粑

TA貢獻1815條經驗 獲得超6個贊

您的e變量名稱令人困惑:根據范圍,它可能具有三個不同的值。嘗試這個 :


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');

    })


});


查看完整回答
反對 回復 2022-11-27
  • 2 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號