如何将处理程序挂在 returns 到 querySelectorAll 函数的元素集合上?
how to hang a handler on a collection of elements that returns to the querySelectorAll function?
我想在点击itemDropDown时做一个下拉菜单,只有第一个可以,其他的不行,querySelectorAll报错,我哪里做错了?我附上了jsfidle所以你可以帮忙,不要注意scss。 http://jsfiddle.net/rhy7pv1f/46/
const itemDropDown = document.querySelectorAll('.menu__list-item.drop__down'),
itemList = document.querySelector('.drop__down-list');
itemDropDown.forEach((buttonItem) => {
buttonItem.addEventListener('click', () => {
itemList.classList.toggle('active');
})
})
您所有的处理程序都会切换您在开始时创建的 itemList
处理程序的 class。
您需要为每个按钮定位相关列表。
const itemDropDown = document.querySelectorAll('.menu__list-item.drop__down');
itemDropDown.forEach((buttonItem) => {
const relatedDropdownList = buttonItem.querySelector('.drop__down-list');
const dropDownLink = buttonItem.querySelector('.menu__list-link');
dropDownLink.addEventListener('click', () => {
relatedDropdownList.classList.toggle('active');
});
})
更新 fiddle
我想在点击itemDropDown时做一个下拉菜单,只有第一个可以,其他的不行,querySelectorAll报错,我哪里做错了?我附上了jsfidle所以你可以帮忙,不要注意scss。 http://jsfiddle.net/rhy7pv1f/46/
const itemDropDown = document.querySelectorAll('.menu__list-item.drop__down'),
itemList = document.querySelector('.drop__down-list');
itemDropDown.forEach((buttonItem) => {
buttonItem.addEventListener('click', () => {
itemList.classList.toggle('active');
})
})
您所有的处理程序都会切换您在开始时创建的 itemList
处理程序的 class。
您需要为每个按钮定位相关列表。
const itemDropDown = document.querySelectorAll('.menu__list-item.drop__down');
itemDropDown.forEach((buttonItem) => {
const relatedDropdownList = buttonItem.querySelector('.drop__down-list');
const dropDownLink = buttonItem.querySelector('.menu__list-link');
dropDownLink.addEventListener('click', () => {
relatedDropdownList.classList.toggle('active');
});
})
更新 fiddle