提问人:Harsh Bhat 提问时间:11/9/2023 更新时间:11/9/2023 访问量:31
无法读取未定义的属性(读取“style”) TypeError:无法读取未定义的属性(读取“style”) 获取代码的此错误
Cannot read properties of undefined (reading 'style') TypeError: Cannot read properties of undefined (reading 'style') Getting this error for the code
问:
我尝试了这个代码块并得到了无法读取未定义的属性(读取“style”)TypeError:无法读取未定义的属性(读取“style”)。有人可以帮忙吗? .
let slideIndex = 0;
function SlideShow(){
let slides = document.getElementsByClassName("slide");
for (let i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}
slides[slideIndex-1].style.display = "block";
setTimeout(SlideShow, 10000);
}
SlideShow()
答:
0赞
AK94
11/9/2023
#1
我想这是你的错误:
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}
slides[slideIndex-1].style.display = "block";
如果它在代码开头找不到任何幻灯片,它将跳过 for 循环。但在这种情况下,您将向 slideIndex 添加 1,因此它的值将为 1。在这种情况下,slideIndex 大于 slides.length (0),slideIndex 将设置为 1。然后,您将访问未定义的幻灯片[1],并且您希望访问未定义的样式。
我建议你用浏览器单步浏览你的JavaScript,看看你的选择器是否得到任何元素。通过此调试,您还应该获得访问 undefined 样式的位置。
评论