简体   繁体   中英

How to fix a stuck loop with two of the same elements?

I have an array imgs with 4 elements (images links). The first two elements of the array are the same. I have also a modal_img.src variable with one link. And I have two buttons: Previous and Next . I want to replace the value of modal_img.src with next value from the array, if the currently compared value from the array is the same as the current value of modal_img.src . It's such switching to the next element.

Code:

    $(next).click(function() {
      for (var a = 0; a < imgs.length; a++){
        if(imgs[a] == modal_img.src) {
          if (a == (imgs.length - 1)) a = -1;
          modal_img.src = imgs[++a];
        }
      }
    });

    $(previous).click(function() {
      for (var a = 0; a < imgs.length; a++){
        if(imgs[a] == modal_img.src) {
          if (a == 0) a = imgs.length;
          modal_img.src = imgs[--a];
        }
      }
    });

Previous button works well, but Next is stucking when I go to the moment of two first the same elements. I can't see any next elements, the loop stops on this "double" element and the Next button looks like it doesn't work. Please help.

Use break; to exit the for loop after the assignment to src . Otherwise it is an infinite loop because of a = -1

$(next).click(function() {
  for (var a = 0; a < imgs.length; a++){
    if(imgs[a] == modal_img.src) {
      if (a == (imgs.length - 1)) a = -1;
      modal_img.src = imgs[++a];
      break;
    }
  }
});

$(previous).click(function() {
  for (var a = 0; a < imgs.length; a++){
    if(imgs[a] == modal_img.src) {
      if (a == 0) a = imgs.length;
      modal_img.src = imgs[--a];
      break;
    }
  }
});

To work around the issue of the image being there twice, a second solution:

This is a solution using a carousel object.

$(next).click(function() {
    carousel.next();
});

$(previous).click(function() {
    carousel.previous();
});

function createCarousel(n) {
    var a = 0;
    return {
        next: function() {
            a = (a+1)%n;
            modal_img.src = imgs[a];
        },
        previous: function() {
            a = (a+n-1)%n;
            modal_img.src = imgs[a];
        }
    };
}

var carousel = createCarousel(imgs.length);

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