我尝试添加“活动类”,当用户单击它时,它将改变导航项的颜色(通过 li 标签显示)。为此,我创建了一个函数来删除所有 li 元素中的活动类。之后,当点击导航项时,我会将活动类添加到该元素。问题是,在运行我的代码时,不是只有一项具有“活动”类,而是所有项都有。我为这个问题找到了很多解决方案,但大多数都使用 jQuery,我对这个库一无所知。我希望有人可以在下面指出我的代码错误。谢谢!
// Find all li tags
const liTags = document.querySelectorAll('li');
// Function to remove the current element has active class
function RemoveActive() {
for (let i = 0; i < liTags.length; i++) {
const currentActiveClass = document.querySelector('.active');
// Remove active class in the current li element
if (currentActiveClass != null) {
liTags[i].classList.remove('active');
}
}
}
// Add the active class to the clicked item
for (let i = 0; i < liTags.length; i++) {
liTags[i].addEventListener('click', function() {
RemoveActive;
liTags[i].classList.add('active');
})
}