简体   繁体   English

如何使用addEventListener在数组内部导航?

[英]How to navigate inside an array using addEventListener?

I'm trying to setup a slider for a project. 我正在尝试为项目设置滑块。 I have an array of objects, every object contains an image and a legend. 我有一个对象数组,每个对象都包含一个图像和一个图例。 Every time a user clicks next or previous button it should display the next or previous object of the array. 每次用户单击下一个或上一个按钮时,它应显示数组的下一个或上一个对象。 Problem is it displays the same image instead of the next, the third, fifth and so on. 问题是它显示的是相同的图像,而不是下一个,第三个,第五个,依此类推。

var index = 0;
var images = [
    {image: 'images/1.jpg', legend: 'Street Art'},
    {image: 'images/2.jpg', legend: 'Fast Lane'},
    {image: 'images/3.jpg', legend: 'Colorful Building'},
    {image: 'images/4.jpg', legend: 'Skyscrapers'},
    {image: 'images/5.jpg', legend: 'City by night'},
    {image: 'images/6.jpg', legend: 'Tour Eiffel la nuit'}
];
var previous = document.getElementById('slider-previous');
var next = document.getElementById('slider-next');

next.addEventListener('click', function() {
    img.src= images[index++].image;
    figcaption.textContent = images[index++].legend;
});
previous.addEventListener('click', function() {
    img.src= images[index--].image;
    figcaption.textContent = images[index--].legend;
});

It works way better, thanks Phil 效果更好,谢谢Phil

next.addEventListener('click', function() {
    ++index;
    img.src= images[index].image;
    figcaption.textContent = images[index].legend;
});

previous.addEventListener('click', function() {
    --index;
    img.src= images[index].image;
    figcaption.textContent = images[index].legend;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM