简体   繁体   中英

Why does my second For Loop in JS not working?

I hope everyone is good. I am presently working on a landing page. I want the visibilities of some divs to be controlled by some buttons, ie when a particular button is clicked, a particular div should display, and when another button is clicked, another div should display. I want this to happen at two different sections of the page. I did for the first section and it works fine, but when I did for the second section, it didn't work. When I comment out the first section, the second starts working. Also when I interchanged their position, the second works while the first refused to work. Kindly help me out with this. Thank you.

 /************************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); }
 //The First Section <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> //The Second Section <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>

Since you have your answer here's an alternative example.

Instead of attaching listeners to all the buttons use event delegation to attach one listener to the buttons' parent element which can catch events from the child elements as they "bubble up" the DOM. When an event is captured a function is called, and if the child element is a button.

Note: your HTML is invalid at the moment - you can't have block elements like headings inside paragraphs or buttons which only accept phrasing content . So I've introduced some semantic mark-up in this example: nav , and article , and section .

 // Cache your elements/containers const answerSection = document.querySelector('.answers'); const nav = document.querySelector('nav'); // Add an event listener to the navigation section nav.addEventListener('click', handleNav); // Accepts a nodelist, and removes the active class // from each node function removeActive(nodelist) { nodelist.forEach(node => node.classList.remove('active')); } // Called when a child element of `nav` is clicked function handleNav(e) { // Check that the child element that was clicked // was a button if (e.target.matches('button')) { // Get all the buttons from `nav`, // remove all the active classes, and then // add an active class to the button that was clicked const buttons = nav.querySelectorAll('button'); removeActive(buttons); e.target.classList.add('active'); const answers = answerSection.querySelectorAll('.answer'); removeActive(answers); // Get the number from the clicked button's dataset const { number } = e.target.dataset; // Form a selector with that number const selector = `[data-number="${number}"]`; // Find that corresponding answer in the answer section const answer = answerSection.querySelector(selector); // Add an active class to that answer answer.classList.add('active'); } }
 nav { display: flex; flex-direction: row; } nav button { padding: 0.25em 0.4em; } nav button:not(:last-child) { margin-right: 0.5em; } nav button:hover { cursor: pointer; background-color: #fffff0; } nav button.active { background-color: lightblue; }.answer { display: none; }.answer.active { display: block; }
 <nav> <button data-number="1" class="active"> What Are Coding Bootcamps? </button> <button data-number="2"> How Do Coding Bootcamps Work? </button> <button data-number="3"> How Do I Choose My Tech Carrer Path? </button> <button data-number="4"> How Long Are The Nest Academy Coding Bootcamps? </button> <button data-number="5"> How Much Do Coding Bootcamps Cost? </button> </nav> <section class="answers"> <article class="answer active" data-number="1"> <h3> What Are Coding Bootcamps? </h3> <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> </article> <article class="answer" data-number="2"> <h3> How Do Coding Bootcamps Work? </h3> <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> </article> <article class="answer" data-number="3"> <h3> How Do I Choose my Tech Career Path? </h3> <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> </article> <article class="answer" data-number="4"> <h3> How Long Are BrainStation's Coding Bootcamps? </h3> <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> </article> <article class="answer" data-number="5"> <h3> How Much Do Coding Bootcamps Cost? </h3> <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> </article> </section>

I solved the problem of loops using forEach instead https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

because maybe the problem is in one of the for < or > (array start with 0)
so with forEach you will never have this problem and is more readable

also, another problem in the school that print "null" because you didn't add data-id but you have data-number

在此处输入图像描述

 const questions = document.querySelectorAll(".btn2"); const answers = document.querySelectorAll(".answer"); const schools = document.querySelectorAll(".btn3"); questions.forEach((question) => { question.addEventListener("click", (e) => { const et = e.target; const activeBtn = document.querySelector(".active"); if (activeBtn) { activeBtn.classList.remove("active"); } et.classList.add("active"); answers.forEach((answer) => { if ( answer.getAttribute("data-number") === question.getAttribute("data-number") ) { answer.style.display = "block"; } else { answer.style.display = "none"; } }) }); }); /*************************Browse Courses**********************/ schools.forEach((school) => { // not data-id let test = school.getAttribute("data-number"); console.log(test); })
 <body> <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> </body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM