【发布时间】: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