我正在处理图像轮播的此代码,但在上一个功能上遇到错误。我想要的是一旦到达最终图像就循环图像。
这是我得到的错误:
未捕获的TypeError:无法读取未定义的属性“ id” 在HTMLDivElement.slide.addEventListener(file:/// C:/ Users / uu / Desktop / New%20folder%20(3)/slider.js:27:25)
HTML代码:
<html>
<head>
<title>image slider project</title>
<link rel="stylesheet" type="text/css" href="slider.css">
</head>
<body>
<div class="container">
<div class="slide">
<img src="./bcg/img5.jpg" id="lastclone">
<img src="./bcg/img1.jpeg">
<img src="./bcg/img2.jpeg">
<img src="./bcg/img3.jpeg">
<img src="./bcg/img4.jpeg">
<img src="./bcg/img5.jpg">
<img src="./bcg/img1.jpeg" id="firstclone">
</div>
</div>
<button class="pbtn">prevbtn</button>
<button class="nbtn">nextbtn</button>
<script type="text/javascript" src="slider.js"></script>
</body>
</html>
JavaScript代码:
var slide = document.querySelector(".slide");
var slideimg = document.querySelectorAll(".slide img");
var prevbtn = document.querySelector(".pbtn");
var nextbtn = document.querySelector(".nbtn");
var counter = 1;
var size = slideimg[0].clientWidth;
slide.style.transform = "translateX(" + (-size * counter) + "px)";
nextbtn.addEventListener("click", next);
prevbtn.addEventListener("click", prev);
function next() {
slide.style.transition = "transform 0.4s ease-in-out";
counter++;
slide.style.transform = "translateX(" + (-size * counter) + "px)";
}
function prev() {
slide.style.transition = "transform 0.4s ease-in-out";
counter--;
slide.style.transform = "translateX(" + (-size * counter) + "px)";
}
slide.addEventListener("transitionend", () => {
if (slideimg[counter].id === "lastclone") {
slide.style.transition = "none";
counter = slideimg.lenght - 2;
slide.style.transform = "translateX(" + (-size * counter) + "px)";
}
});
答案 0 :(得分:0)
如果遇到此类问题,请尝试考虑发生这种情况的可能原因。
在这种情况下,错误很简单:未捕获的TypeError:无法读取HTMLDivElement.slide.addEventListener(file:/// C:/ Users / uu / Desktop / New%处未定义的属性'id' 20folder%20(3)/slider.js:27:25)
这意味着您在第27行第25列上遇到错误。它试图读取未定义的属性“ id”(slideimg [counter] .id )。意思是slideimg [counter]返回未定义。
要完成调试过程,您有3种选择:
1)您只需查看代码即可发现错误
2)添加在此特定位置使用的变量的日志:
slide.addEventListener("transitionend", () => {
console.log( slideimg, counter );
if (slideimg[counter].id === "lastclone") {
slide.style.transition = "none";
counter = slideimg.lenght - 2;
slide.style.transform = "translateX(" + (-size * counter) + "px)";
}
});
3)使用浏览器的调试功能来深入了解幕后情况:
slide.addEventListener("transitionend", () => {
// by adding this statement here, code execution will stop at runtime at this
// particular place
debugger;
if (slideimg[counter].id === "lastclone") {
slide.style.transition = "none";
counter = slideimg.lenght - 2;
slide.style.transform = "translateX(" + (-size * counter) + "px)";
}
});
更多内容:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger