var navElements = document.querySelectorAll('a');
//looping through each anchor element
navElements.forEach(function(element){
//adding click event on each anchor element
element.addEventListener('click',function(e){
//stop default behaviour
e.preventDefault();
//select current active element
let active = document.querySelector('.selected');
active?.classList.remove('selected'); //remove class
this.classList.add('selected'); //add class to current click element
});
});
2条答案
按热度按时间sqyvllje1#
aurhwmvo2#
向每个元素添加事件,然后单击链接执行类的添加/删除。