我的JavaScript第二个for循环为何无法正常工作?
按钮切换Div显示功能异常排查与修复
问题现象
- 开发着陆页时,两个按钮控制Div显示的区域,仅第一个区域功能正常,第二个区域完全失效
- 注释第一个区域代码后,第二个区域功能恢复正常
- 交换两个区域代码顺序后,原本正常的区域失效,原本失效的区域恢复正常
原始问题代码
JavaScript部分
/************************FAQ Section**************/ const questions = document.querySelectorAll(".btn2"); for (let j = 0; j <= questions.length; j++){ questions[j].addEventListener('click', (e) => { const et = e.target; const activeBtn = document.querySelector(".active"); if (activeBtn){ activeBtn.classList.remove("active"); } et.classList.add("active"); const answers = document.querySelectorAll(".answer"); for (let x = 0; x <= answers.length; x++){ if(answers[x].getAttribute("data-number") === questions[j].getAttribute("data-number")){ answers[x].style.display = "block"; } else { answers[x].style.display = "none"; } } }); } /*************************Browse Courses**********************/ const schools = document.querySelectorAll(".btn3"); for (let y = 0; y <= schools.length; y++){ let test = schools[y].getAttribute("data-id"); console.log(test); }
HTML部分
<!-- 第一区域 --> <div class="container-fluid mt-4"> <div class="btn-group"> <button data-number="1" class="btn btn2 active"> <h5>What Are Coding Bootcamps?</h5> <i class="fa-solid fa-angle-right"></i> </button> <button data-number="2" class="btn btn2"> <h5>How Do Coding Bootcamps Work?</h5> <i class="fa-solid fa-angle-right"></i> </button> <button data-number="3" class="btn btn2"> <h5>How Do I Choose My Tech Carrer Path?</h5> <i class="fa-solid fa-angle-right"></i> </button> <button data-number="4" class="btn btn2"> <h5>How Long Are The Nest Academy Coding Bootcamps?</h5> <i class="fa-solid fa-angle-right"></i> </button> <button data-number="5" class="btn btn2"> <h5>How Much Do Coding Bootcamps Cost?</h5> <i class="fa-solid fa-angle-right"></i> </button> </div> <div class="answer" data-number="1"> <p> <h5>What Are Coding Bootcamps?</h5> <p> Coding bootcamps are short, intensive training coding programs and tech courses that give students the skills they need for new careers in technology. Programming bootcamps and code schools like BrainStation have become an increasingly popular alternative to a four-year computer science degree, allowing students to gain real-world experience under the instruction of top industry professionals. While "coding bootcamps" as a term has come to be used for digital skills training across disciplines, including courses and programs relating to web development, software development, data science, UX design, and digital marketing, the term originally was meant to describe short-term, intensive training programs in full-stack web development, software development, or software engineering. As one of the best coding bootcamps, BrainStation provides hands-on, project-based learning, allowing students with no prior experience to learn how to use programming languages like HTML, CSS, JavaScript, Python, SQL, and more. The goal of our coding bootcamps is to prepare you for a new career in web development, software development and engineering, data science, design, security, digital marketing, or related tech fields. To that end, bootcamp graduates also benefit from ongoing, personalized career services meant to provide guidance and support during the job search. </p> </p> </div> <div class="answer" data-number="2"> <p> <h5>How Do Coding Bootcamps Work?</h5> <p> Coding bootcamps work by giving students hands-on experience with the key programming languages, knowledge areas, and technical skills needed for a career in technology. The best coding bootcamps are taught by experienced professionals who know what employers are looking for. Many bootcamp students are looking to change careers, so the best bootcamps help with the job search, including career services, a network of hiring partners, and opportunities to build professional networks through events and guest lectures. Ultimately, coding bootcamp students learn the skills and develop the project portfolio necessary to land a job in web and software development, software engineering, data science, UX design, digital marketing, or other tech fields. </p> </p> </div> <div class="answer" data-number="3"> <p> <h5>How Do I Choose my Tech Career Path?</h5> <p> When trying to determine your tech career path, the first step is to understand where your interests and passions truly lie. Do you have a good sense of computer science fundamentals? Are you excited about the idea of building a website? Take a look at full-stack web development and the kinds of careers you can have after taking a web development bootcamp. Are you good with numbers and like identifying trends (that would have remained hidden)? A career in data science might be for you. Asking yourself questions like these will help guide your job search and the kind of training you need. From there, take stock of the skills and experience you currently have – whether or not they are in computer science. Is there any overlap with skills that are most in demand? Does your education and professional experience lend itself to an emerging field like data science, software, development, or digital marketing? </p> </p> </div> <div class="answer" data-number="4"> <p> <h5>How Long Are BrainStation's Coding Bootcamps?</h5> <p> BrainStation's coding bootcamps generally take three months to complete on a full-time basis — 12 weeks. In that time, you will develop a comprehensive understanding of web development, data science, user experience design, or digital marketing fundamentals, and learn how to apply these new skills and knowledge. BrainStation bootcamps are immersive and project-based, allowing you to build a portfolio of completed projects by the end of the bootcamp. For students seeking more flexibility, BrainStation also offers part-time bootcamps, which are completed over eight months. </p> </p> </div> <div class="answer" data-number="5"> <p> <h5>How Much Do Coding Bootcamps Cost?</h5> <p> Tuition for full-time coding bootcamps can vary depending on the field of study, the location of the campus, the method of study chosen (online or in-person), or how comprehensive the course is. Some programming bootcamps and code schools could be relatively inexpensive or quick to complete, but might not cover the full range of skills and competencies needed, especially for students interested in full-stack web development. </p> </p> </div> </div> <!-- 第二区域 --> <div class="container-fluid bg-primary"> <div class="row"> <div class="col-4 bg-dark"></div> <div class="col-8 bg-danger"> <div class="btn-group"> <button data-number="1" class="btn btn3 active-course"> Tech </button> <button data-number="2" class="btn btn3"> Enter </button> <button data-number="3" class="btn btn3"> Creative </button> </div> </div> </div> </div> <div class="container"> <div data-number="1" class="browse-course1"> <div class="row"> <div class="col pt-5 bg-light"></div> <div class="col pt-5 bg-success"></div> <div class="col pt-5 bg-secondary"></div> <div class="col pt-5 bg-warning"></div> <div class="col pt-5 bg-info"></div> </div> </div> <div data-number="2" class="browse-course1"> <div class="row"> <div class="col pt-5 bg-light"></div> <div class="col pt-5 bg-success"></div> <div class="col pt-5 bg-secondary"></div> <div class="col pt-5 bg-warning"></div> <div class="col pt-5 bg-info"></div> </div> </div> <div data-number="3" class="browse-course1"> <div class="row"> <div class="col pt-5 bg-light"></div> <div class="col pt-5 bg-success"></div> <div class="col pt-5 bg-secondary"></div> <div class="col pt-5 bg-warning"></div> <div class="col pt-5 bg-info"></div> </div> </div> </div>
问题根源
两个for循环都使用了<=作为终止条件,导致数组越界错误:
document.querySelectorAll()返回类数组对象,索引从0开始,有效索引范围是0到length-1- 当循环条件为
j <= questions.length时,最后一次循环会访问questions[questions.length],该位置为undefined,调用addEventListener时直接抛出错误,中断后续代码执行 - 第二个区域的代码根本没有机会执行,因此功能失效
修复后的完整代码
JavaScript部分
/************************FAQ Section**************/ const questions = document.querySelectorAll(".btn2"); // 改用forEach避免索引越界,同时避免闭包问题 questions.forEach(btn => { btn.addEventListener('click', (e) => { // 确保点击目标是按钮本身(避免子元素触发) const targetBtn = e.target.closest('.btn2'); // 移除同组其他按钮的激活状态 const activeBtn = document.querySelector(".btn2.active"); if (activeBtn) { activeBtn.classList.remove("active"); } targetBtn.classList.add("active"); // 切换对应答案的显示状态 const targetNumber = targetBtn.getAttribute("data-number"); document.querySelectorAll(".answer").forEach(answer => { answer.style.display = answer.getAttribute("data-number") === targetNumber ? "block" : "none"; }); }); }); /*************************Browse Courses**********************/ const schools = document.querySelectorAll(".btn3"); schools.forEach(btn => { btn.addEventListener('click', (e) => { const targetBtn = e.target.closest('.btn3'); const activeBtn = document.querySelector(".btn3.active-course"); if (activeBtn) { activeBtn.classList.remove("active-course"); } targetBtn.classList.add("active-course"); const targetNumber = targetBtn.getAttribute("data-number"); document.querySelectorAll(".browse-course1").forEach(course => { course.style.display = course.getAttribute("data-number") === targetNumber ? "block" : "none"; }); }); });
HTML部分(仅调整初始隐藏状态)
<!-- 第一区域 --> <div class="container-fluid mt-4"> <!-- 按钮组代码不变 --> <div class="answer" data-number="1"> <!-- 内容不变 --> </div> <div class="answer" data-number="2" style="display: none;"> <!-- 内容不变 --> </div> <div class="answer" data-number="3" style="display: none;"> <!-- 内容不变 --> </div> <div class="answer" data-number="4" style="display: none;"> <!-- 内容不变 --> </div> <div class="answer" data-number="5" style="display: none;"> <!-- 内容不变 --> </div> </div> <!-- 第二区域 --> <div class="container-fluid bg-primary"> <!-- 按钮组代码不变 --> </div> <div class="container"> <div data-number="1" class="browse-course1"> <!-- 内容不变 --> </div> <div data-number="2" class="browse-course1" style="display: none;"> <!-- 内容不变 --> </div> <div data-number="3" class="browse-course1" style="display: none;"> <!-- 内容不变 --> </div> </div>
内容的提问来源于stack exchange,提问作者Abubakar
相关产品推荐
相关产品推荐

