prevImg
和
nextImg
不工作是因为:
-
这些元素没有
order
属性,所以你得到
null
从
e.target.getAttribute("order")
和
-
在这种情况下
奈克斯替格
,如果它
做
如果有这个属性,它的值将是一个字符串,所以
x = x + 1
将是
字符串连接
,而不是添加。
相反,在变量中维护当前索引,请参见
***
评论:
var imgs = ["https://i.stack.imgur.com/mucrb.png",
"https://i.stack.imgur.com/0BH67.png",
"https://i.stack.imgur.com/KdNeR.png",
"https://i.stack.imgur.com/StOAl.png",
"https://i.stack.imgur.com/yhvqi.png"];
var bs = document.getElementsByTagName("button"); // *** Added var
for(var i =0;i<bs.length;i++){
bs[i].addEventListener("click",showImg);
}
var pLeft =document.getElementById("left"); // *** Added var
pLeft.addEventListener("click",prevImg);
var pRight =document.getElementById("right"); // *** Added var
pRight.addEventListener("click",nextImg);
var currentIndex = 0; // ***
// *** Reusable function so we aren't repeating ourselves constantly below
function displayImage(src) {
// *** Notice the .src property
document.getElementById("loopImg").src = src;
}
displayImage(imgs[0]); // *** Show the first image
function showImg(e){
// *** Note the unary + to convert to number
currentIndex = +e.target.getAttribute("order") - 1;
displayImage(imgs[currentIndex]);
}
function nextImg(e){
currentIndex = (currentIndex + 1) % imgs.length; // *** Wraps around
displayImage(imgs[currentIndex]);
}
function prevImg(e){
currentIndex = (currentIndex - 1 + imgs.length) % imgs.length; // *** Wraps around
displayImage(imgs[currentIndex]);
}
#main{
width:600px;
height:400px;
border:1px solid red;
display:grid;
grid-template-columns:60px auto 60px;
grid-template-rows:60px auto 60px;
grid-template-areas:"des des des"
"left loopImg right"
"buttons buttons buttons";
margin:0 auto;
}
#des{
grid-column: 1/4;
grid-row:1/2;
margin:auto;
}
#loopImg{
grid-column:2/3;
grid-row:2/3;
border:1px solid green;
margin:auto;
}
#left{
grid-column:1/2;
grid-row:2/3;
margin:auto;
}
#right{
grid-column:3/4;
grid-row:2/3;
margin:auto;
}
#buttons{
grid-column:1/4;
grid-row:3/4;
margin:auto;
}
button{
width:30px;
height:30px;
border:1px solid green;
border-radius:50%;
}
img{
width:200px;
height:200px;
}
<div id="main">
<div id="des">loop images</div>
<img id="loopImg" src="" alt="">
<p id="left"><<!-- *** Note using entity for '<' --></p>
<p id="right">></p>
<div id="buttons">
<button order="1" >1</button>
<button order="2" >2</button>
<button order="3" >3</button>
<button order="4" >4</button>
<button order="5" >5</button>
</div>
</div>
旁注:我没有对代码或类似的东西进行全面审计。我确实注意到,在很多地方,最初的代码成为了我所说的
The Horror of Implicit Globals
. 确保声明变量(
bs
,
x
,
pLeft
,
pRight
,在最窄的范围内。