简体   繁体   中英

Replace numbers by a calculation in Javascript

I would like to know if there's a way in javascript to replace [0] by a calculation : [+1] and [-1]

Example of my situation :
I have a gallery presenting 6 images, I want to use keyboard arrows to navigate.
When the current image is the 4th, if I let [1] in my script to go to the previous image by pressing keyboard arrow, the first image appears instead of the third.
Any idea ? Thanks.

Script :

$(document).on('keyup', function (e) {
    switch (e.which) {
        case 37:
            $('.prev')[0].click();
            break;

        case 39:
            $('.next')[0].click();
            break;
    }
});

You need to store current position

var current = 0;
$(document).on('keyup', function (e) {
    switch (e.which) {
        case 37:
            $('.prev')[--current].click();
            break;

        case 39:
            $('.next')[++current].click();
            break;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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