[英]How can I active a link when click, and deactivate the others in javascript?
I'm trying to handle just one element when I click in the link, but when I click on another it doesn't remove the active to other links.当我单击链接时,我试图只处理一个元素,但是当我单击另一个元素时,它不会删除其他链接的活动。 Can anyone help me?
谁能帮我? Here's my code.
这是我的代码。 .
. .
.
let parentT = document.querySelector('.menu-item'); //PARENT
let allEl = parentT.querySelectorAll('a'); // ELEMENTS INSIDE PARENT
allEl.forEach(elem =>{
elem.addEventListener('click', (event) => {
event.preventDefault();
event.target.setAttribute('class', 'active');
if(event.target.classList == "active") {
console.log(event.target);
}
});
});
I've try some methods but with no result.我尝试了一些方法但没有结果。
I think this is what you wanted.我想这就是你想要的。 this code loops through all anchor elements when one is clicked and removes that active class from all of them, then adds the active class to the clicked element.
单击一个元素时,此代码循环遍历所有锚元素,并从所有元素中删除活动的 class,然后将活动的 class 添加到单击的元素。
let parentT = document.querySelector('.menu-item'); //PARENT let allEl = parentT.querySelectorAll('a'); // ELEMENTS INSIDE PARENT allEl.forEach(elem =>{ elem.addEventListener('click', (event) => { event.preventDefault(); allEl.forEach(el => { el.classList.remove('active'); }); event.target.classList.add('active'); }); });
.active { color: red; }
<div class="menu-item"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> <a href="#">Link 4</a> <a href="#">Link 5</a> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.