简体   繁体   中英

jquery image carousel doesn't work after two clicks

I'm trying to make a simple jquery image carousel.

Here's my complete code: http://jsfiddle.net/6fwbS/19/

The following function gets called when you click the "increase" button to slide the images to the left and make one disappear. The problem that I'm experiencing is that it only seems to work once. The first time you click it loads the next image into the container. The second time you click it calls that alert twice. I don't know why it is calling the alert twice on the second click. The third time you click it it does not alert at all. Any help would be greatly appreciated. For an example of the end goal click on decrease after you run it. What I'm ultimately trying to do here is get a new image into the container when each button is clicked and cycle back and forth through the images.

function slide_img_left() {

    var imgs = imgArr.length;

    a++;
    if (a >= imgs) {
        a = 0;
    }

    b = a - 1;
    c = a + 1;

    if (b < 0) {
        b = imgs - 1;
    }
    if (c >= imgs) {
        c = 0;
    }

    $('.left_slot').animate({
        opacity: 0,
        left: '-=50px'
    }, 300, function() {
        $('.left_slot').remove();
    });

    $('.middle_slot').animate({
        left: '-=50px'
    }, 300, function() {
        $('.middle_slot').attr('class', 'left_slot');
        $('.right_slot').attr('class', 'middle_slot');
        alert(c);

    });

    $('.right_slot').animate({
        left: '-=50px'
    }, 300);

    $("#basic_div").append(imgArr[c][0]);
        $("#varsDiv").html(" var b = " + b + " var a = " + a + " var c = " + c);

}

The problem is that $('.left_slot') in your complete callback may refer to the new left slot that was created by one of the other complete callbacks.

This is the relevant part of slide_img_left() fixed so that it alerts only once:

var left = $('.left_slot');
var middle = $('.middle_slot');
var right = $('.right_slot');

left.animate({
    opacity: 0,
    left: '-=50px'
}, 300, function() {
    left.remove();
});


middle.animate({
    left: '-=50px'
}, 300, function() {
    middle.attr('class', 'left_slot');
    right.attr('class', 'middle_slot');
    alert(c);

});

right.animate({
    left: '-=50px'
}, 300);

Link to updated jsFiddle ( Edit: updated the link to point to a forked version.)

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