2 回答

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
您正在嘗試將事件偵聽(tīng)器添加到節(jié)點(diǎn)集合(querySelectorAll for.nav-link與querySelectorfor .nav-toggle)。您可以迭代集合并將click事件偵聽(tīng)器添加到每個(gè)項(xiàng)目,或者僅偵聽(tīng) 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貢獻(xiàn)1893條經(jīng)驗(yàn) 獲得超10個(gè)贊
您必須使用循環(huán),因?yàn)閝uerySelectorAll返回一個(gè)數(shù)組。
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 關(guān)注
- 163 瀏覽
添加回答
舉報(bào)