提问人:Mandy23 提问时间:9/23/2023 更新时间:9/23/2023 访问量:48
无法设置 undefined 的属性(设置“onclick”)
Cannot set properties of undefined (setting 'onclick')
问:
尽管我正在传递节点元素,但出现 onclick 应用于未定义的错误。
[HTML全文]
<div class="gallery">
<img src="image1.png" id="prdImg" />
<div class="control">
<span class="btn active"></span>
<span class="btn"></span>
<span class="btn"></span>
</div>
</div>
JS系列
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");
};
}
答:
1赞
Surju Mk
9/23/2023
#1
在 for 循环中,更改 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");
};
}
评论
<script>
<div>