此函数应在文档中搜索具有值为“graphicDesign”的“data-info”属性的任何元素,然后在这些元素上切换类“hideMe”。
它在控制台中返回正确数量的元素,但在 classList 切换时中断。
我尝试过其他方法,例如按类名查找元素然后切换,但这也不起作用。
function toggleGraphicDesign() {
let graphicDesignElements = document.querySelectorAll('[data-info="graphicDesign"]');
console.log(graphicDesignElements.length);
graphicDesignElements.classList.toggle('hideMe');
}
最佳答案
querySelectorAll()
返回一个 NodeList 而不是单个元素。根据 MDN
The Document method
querySelectorAll()
returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
您需要使用 forEach()
遍历所有元素并切换每个元素的类。
function toggleGraphicDesign() {
let graphicDesignElements = document.querySelectorAll('[data-info="graphicDesign"]');
console.log(graphicDesignElements.length);
graphicDesignElements.forEach(x => x.classList.toggle('hideMe'))
}
关于javascript - 如何在原生 JavaScript 中实现 'toggle class' 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56185462/