【问题标题】:What's wrong with my code, click event fires only once JavaScript?我的代码有什么问题,单击事件仅触发一次 JavaScript?
【发布时间】:2021-11-12 15:50:57
【问题描述】:

循环只工作一次,然后什么也没有发生。我有三个推荐,只能前进或后退一次。谢谢帮助!

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);
});

【问题讨论】:

  • 您的控制台有错误吗?请发minimal reproducible example
  • 您的代码运行良好,目前我们能提供给您的不多。检查您是否拥有带有testimonial 的所有元素。此外,在您的函数中设置断点并查找任何运行问题。
  • 您可以使用Stack Snippet 来生成可执行文件minimal reproducible example
  • 控制台没有错误,所有元素都带有证明。

标签: javascript loops


【解决方案1】:

我会使用“隐藏”类来隐藏非活动的推荐,而不是直接操作元素的样式。此外,您的导航逻辑可以简化为模运算。

您最初发布的代码似乎运行良好,但它似乎充满了冗余(代码重用)。它还缺乏结构化流程(可读性)。

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>

【讨论】:

  • testimonial.classList.toggle('hidden', currIndex !== index) 这个表达对我来说很新鲜,谢谢。
猜你喜欢
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多