我在使用不同屏幕尺寸的导航栏菜单处理项目时遇到此错误 "Cannot read property 'forEach' of undefined"

i get this error while working on project with nav bar menu in different screen sizes "Cannot read property 'forEach' of undefined"

这里是我的javascript错误发生的代码。

const navSlide = () => {
    const burger = document.querySelector('.burger');
    const nav = document.querySelector('.nav-links');
    const navLinks = document.querySelectorAll('.nav-links li');

    burger.addEventListener('click', () => {

        nav.classList.toggle('nav-active');
        
        navLinks.array.forEach((link, index) => {
            if(link.style.animation)
            {
                link.style.animation = '';
            }
            else
            {
                link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 1.5}s`;
            }
        });
                  
        burger.classList.toggle('toggle');
    });
}
navSlide();

如果你们中有人需要HTML和CSS代码请告诉我。

替换:

 const navLinks = document.querySelectorAll('.nav-links li');

与:

const navLinks = [...document.querySelectorAll(".nav-links li")];

(如果您总是在 dom 中包含这些项目,否则您会收到语法错误)

然后尝试:

navLinks.forEach(...)

您的 querySelectorAll 将 return 一个 NodeList,因此无需指定“数组”:navLinks.array.forEach 只需使用 navLinks.forEach,您的代码应该可以工作。