2 回答
TA贡献1807条经验 获得超9个赞
您正在尝试将事件侦听器添加到节点集合(querySelectorAll for.nav-link与querySelectorfor .nav-toggle)。您可以迭代集合并将click事件侦听器添加到每个项目,或者仅侦听 s 的父元素.nav-link:
const navToggle = document.querySelector('.nav-toggle')
// replace this with something more sensible
const navLinkParent = document.querySelector('.nav-link').parentElement;
navToggle.addEventListener('click', () => {
document.body.classList.toggle('nav-open')
})
// this is adding a click listener to ONE element
navLinkParent.addEventListener('click', (event) => {
// check if the clicked element matches what you're after
if (event.target.classList.contains('nav-link')) {
document.body.classList.remove('nav-open')
}
})
TA贡献1893条经验 获得超10个赞
您必须使用循环,因为querySelectorAll返回一个数组。
const navToggle = document.querySelector('.nav-toggle')
const navLink = document.querySelectorAll('.nav-link')
navToggle.addEventListener('click', () => {
document.body.classList.toggle('nav-open')
})
for (var i = 0; i < navLink.length; ++i) {
navLink[i].addEventListener('click', () => {
if(navToggle.classList.contains('nav-toggle')){
(navToggle.classList.remove('nav-toggle');
}
});
}
- 2 回答
- 0 关注
- 92 浏览
添加回答
举报