在 for 循环中,将
i <= btn.length
更改为 i < btn.length
。
const prdImg = document.getElementById("prdImg");
const btn = document.getElementsByClassName("btn");
for (let i = 0; i < btn.length; i++) {
btn[i].onclick = function () {
prdImg.src = `image${i + 1}.png`;
for (bt of btn) {
bt.classList.remove("active");
}
this.classList.add("active");
};
}