首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我在JS中的第二个For循环不能工作?

为什么我在JS中的第二个For循环不能工作?
EN

Stack Overflow用户
提问于 2022-08-19 11:23:25
回答 2查看 73关注 0票数 0

我希望每个人都很好。我现在正在写一个登陆页。我希望某些div的可见性由一些按钮控制,即当一个特定的按钮被单击时,一个特定的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);
}
代码语言:javascript
复制
//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>

EN

回答 2

Stack Overflow用户

发布于 2022-08-19 11:37:37

我解决了使用forEach而不是对象/数组/forEach循环的问题

因为问题可能出在一个for <> (数组从0开始)。 因此,对于forEach,您永远不会遇到这个问题,而且也会更易读,因为您没有添加data-id,但是您有data-number,所以在学校中打印"null“的另一个问题是

代码语言:javascript
复制
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);
})
代码语言:javascript
复制
<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>

票数 1
EN

Stack Overflow用户

发布于 2022-08-19 12:34:40

既然你有你的答案,这里有另一个例子。

而不是将侦听器附加到所有按钮,而是使用事件委托将一个侦听器附加到按钮的父元素,当其子元素“冒泡”DOM时,它可以捕捉子元素中的事件。捕获事件时,调用函数,如果子元素是按钮,则调用函数。

注意:您的HTML当前是无效的-您不能在段落或按钮中有块元素,比如只接受短语内容的标题。在这个例子中,我介绍了一些语义标记:navarticlesection

代码语言:javascript
复制
// 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');
  
  }
}
代码语言:javascript
复制
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; }
代码语言:javascript
复制
<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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73416030

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档