Кнопка слайдера Javascript - PullRequest
0 голосов
/ 07 марта 2019

Я работаю над слайдером изображений Javascript. Я хотел бы понять код ниже, потому что здесь var i= image.length и тот же var i принимают команду цикла. Я запутался в том, как это работает.

<script type="text/javascript">

    var slider_content = document.getElementById('box');

    var image = ['a','b', 'c', 'd','e'];

    var i = image.length;


    // function for next slide 

    function nextImage() {
        if (i<image.length) {
            i= i+1;
        } else {
            i = 1;
        }
        slider_content.innerHTML = "<img src="+image[i-1]+".jpg>";
    }


    // function for prew slide

    function prewImage(){

        if (i<image.length+1 && i>1) {
            i= i-1;
        } else {
            i = image.length;
        }
        slider_content.innerHTML = "<img src="+image[i-1]+".jpg>";

    }

1 Ответ

1 голос
/ 07 марта 2019

Код прост и не имеет цикла for, как сказал Ашкан. Я постараюсь объяснить код в соответствии с моим пониманием. В начале, где

var i = image.length

, код получает длину изображения, которая всегда равна 5 для вашего случая.

Когда вызывается следующая функция,

function nextImage() {
  //When the next image function is called, the code first checks that the value i is not
  //equal or greater than image.length, since we cannot really increment i to be greater 
  //than the available images.

        if (i<image.length) {
  //Our current index is either 1, 2, 3, or 4 so we can set our current index to 5 and 
  //show image 5

            i= i+1;
        } else {
  //Our index is 5 so we have to set our index to 1. 
  //We cannot increment because we dont have image 6 or more

            i = 1;
        }
  //Show image at current index. Seems like your images are starting from Image 0 to 
  // image 4 so we subtract one.

        slider_content.innerHTML = "<img src="+image[i-1]+".jpg>";
    }

Когда вызывается функция предыдущего изображения,

function prewImage(){
  //When the previous image function is called, the code first checks that the value i is not
  //less than image.length and that our current index is greater than 1.

        if (i<image.length+1 && i>1) {
  //Our current index is equal or greater than 2 so we can set it to a value just below
  //it. Notice this can never be 1 since 1-1 = 0 which is not a valid index
            i= i-1;
        } else {
  //Current index is 1
  //If the current index is 1, set it to the length of the images which is also the index
  // of the last image, that is 5.
            i = image.length;
        }
  //Show image at current index. Seems like your images are starting from Image 0 to 
  // image 4 so we subtract one.
        slider_content.innerHTML = "<img src="+image[i-1]+".jpg>";

    }

Надеюсь, это поможет, спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...