[英]What's wrong with my code, click event fires only once JavaScript?
The loop works only once and then nothing happens.循环只工作一次,然后什么也没有发生。 I have three testimonials, and can go only once forward or backwords.Thanks for help!
我有三个推荐,只能前进或后退一次。感谢您的帮助!
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);
});
I would use a "hidden" class to hide the non-active testimonials instead of manipulating the element's style in-line.我会使用“隐藏”类来隐藏非活动的推荐,而不是在线操纵元素的样式。 Also, your navigation logic can be simplified to a modulo operation.
此外,您的导航逻辑可以简化为模运算。
The code your originally posted seemed to work out well, but it seems to cluttered with redundancy (code reuse).您最初发布的代码似乎运行良好,但似乎充满了冗余(代码重用)。 It also lacks structural flow (readability).
它还缺乏结构流(可读性)。
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.