我正在创建一个非常基本的程序,允许用户使用一组按钮循环浏览图像,而我遇到的主要问题是它似乎只是在选择数组中的随机点。例如,数组从 1 开始,但它显示位置 0 的图像,或者假设我尝试在图像中向后循环,如果我从 0(这意味着位置 3)开始,它'我将跳回到位置 1 的图像。我无法理解它。
var i = 0;
var imageArr = [];
imageArr[0] = 'img/img_BMW.jpg';
imageArr[1] = 'img/img_Chr.jpg';
imageArr[2] = 'img/img_Mas.jpg';
imageArr[3] = 'img/img_Merc.jpg';
function imageCycle(){
document.imgCycle.src = imageArr[i];
if(i < imageArr.length - 1){
i++
}
else{
i = 0;
}
console.log(i);
}
function imagePrev(){
document.imgCycle.src = imageArr[i];
if(i == imageArr.length - 1){
i = 3;
}
else{
i--;
}
}
<img name="imgCycle" width="440" height="250"/>
<ul>
<li><button type="button" id="back-Btn" onclick="imagePrev();">Back</button></li>
<li><button type="button" id="forward-Btn" onclick="imageCycle();">Forward</button></li>
</ul>
最佳答案
您可以添加一个方法来转到您想要的下一个索引,并让此函数确保索引不会越界。
作为旁注,像通过 onclick
属性那样绑定(bind)事件处理程序不再是真正的首选方式。尝试改用 addEventListener
。
var i = 0;
// Use some actuale images so we can see what happens in the DOM.
var imageArr = [
'//placehold.it/300/200/?text=1',
'//placehold.it/300/200/?text=2',
'//placehold.it/300/200/?text=3',
'//placehold.it/300/200/?text=4'
];
/**
* A method to alter the index. Pass 1 to go to the next slide and -1 to go to
* the previous slide. It will make sure the index is never out of bounds.
*/
function getNextIndex(index, modifier) {
// Add the modifier to the index.
index = index + modifier;
// Check if the index is less than zero, this is unvalid and we will reset the index
// to the last item in the image array. When the index is more than 0, check if it exceeds
// the index for the last item in the array. In this case reset it to 0 so we go back to
// the first image.
if (index < 0) {
index = imageArr.length - 1;
} else if (index >= imageArr.length) {
index = 0;
}
return index;
}
function updateImage(index) {
document.imgCycle.src = imageArr[index];
}
function goToNextImage() {
i = getNextIndex(i, 1);
updateImage(i);
}
function goToPreviousImage() {
i = getNextIndex(i, -1);
updateImage(i);
}
updateImage(0);
<img name="imgCycle" width="440" height="250"/>
<ul>
<li><button type="button" id="back-Btn" onclick="goToPreviousImage();">Back</button></li>
<li><button type="button" id="forward-Btn" onclick="goToNextImage();">Forward</button></li>
</ul>
关于javascript - 为什么这个数组只是选择随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56275205/