簡體   English   中英

我的代碼有什么問題,單擊事件只觸發一次 JavaScript?

[英]What's wrong with my code, click event fires only once JavaScript?

循環只工作一次,然后什么也沒有發生。 我有三個推薦,只能前進或后退一次。感謝您的幫助!

const nextBtn = document.querySelector(".next-btn");
const prevBtn = document.querySelector(".prev-btn");
const testimonials = document.querySelectorAll(".testimonial");

let index = 0;
window.addEventListener("DOMContentLoaded", function () {
  show(index);
});
function show(index) {
  testimonials.forEach((testimonial) => {
    testimonial.style.display = "none";
  });
  testimonials[index].style.display = "flex";
}

nextBtn.addEventListener("click", function () {
  index++;
  if (index > testimonials.length - 1) {
    index = 0;
  }
  show(index);
});

prevBtn.addEventListener("click", function () {
  index--;
  if (index < 0) {
    index = testimonials.length - 1;
  }
  show(index);
});

我會使用“隱藏”類來隱藏非活動的推薦,而不是在線操縱元素的樣式。 此外,您的導航邏輯可以簡化為模運算。

您最初發布的代碼似乎運行良好,但似乎充滿了冗余(代碼重用)。 它還缺乏結構流(可讀性)。

 const modulo = (n, m) => (m + n) % m, moduloWithOffset = (n, m, o) => modulo(n + o, m); const nextBtn = document.querySelector('.next-btn'), prevBtn = document.querySelector('.prev-btn'), testimonials = document.querySelectorAll('.testimonial'); let index = 0; const show = (index) => { testimonials.forEach((testimonial, currIndex) => { testimonial.classList.toggle('hidden', currIndex !== index) }); } const navigate = (amount) => { index = moduloWithOffset(index, testimonials.length, amount); show(index); } // Create handlers const onLoad = (e) => show(index); const onPrevClick = (e) => navigate(-1); const onNextClick = (e) => navigate(1); // Add handlers window.addEventListener('DOMContentLoaded', onLoad); nextBtn.addEventListener('click', onNextClick); prevBtn.addEventListener('click', onPrevClick);
 .testimonial { display: flex; } .testimonial.hidden { display: none; }
 <div> <button class="prev-btn">Prev</button> <button class="next-btn">Next</button> </div> <div> <div class="testimonial">A</div> <div class="testimonial">B</div> <div class="testimonial">C</div> <div class="testimonial">D</div> <div class="testimonial">E</div> <div class="testimonial">F</div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM