2016-06-13 4 views
2

자동 슬라이드 쇼를 만들려고하지만이 메시지가 계속 나타나고 그 이유를 모르겠습니다.정의되지 않은 'removeClass'속성을 읽을 수 없습니다.

HTML :

<section id="slideshow"> 
    <div class="auto-slideshow"> 
     <img src="img/pic1.jpg" alt="" class="slide show"> 
     <img src="img/pic2.jpg" alt="" class="slide hide"> 
     <img src="img/pic3.jpg" alt="" class="slide hide"> 
    </div> 
</section> 

"표시"와 "닫기"클래스는 각각 '블록'과 '없음'으로 표시 설정.

자바 스크립트 :

autoSlideshow(); 

var mySlides = $('#slideshow .slide'); 
var slides = []; 
mySlides.each(function() { 
    slides.push($(this)); 
}); 

function autoSlideshow() { 
    var index; 
    var next; 

    mySlides.each(function() { 
     if ($(this).hasClass('show')) { 
      index = $(this).index(); 
      next = index+1; 

      $(this).removeClass('show').addClass('hide'); 
      slides[next].removeClass('hide').addClass('show'); 

      console.log('The index is: '+index); 
      console.log('The next one is: '+next); 
     }; 
    }); 
    setInterval(autoSlideshow, 3000); 
}; 

어떤 조언이나 보정을 많이 감사합니다.

+3

을 다음이 정의 될 수 있기 때문에 그것은있을 수 슬라이드 – Li357

+0

의 양 이상이라면 그 슬라이드 [다음] 자바 스크립트 객체가 아닌 것입니다 jQuery 객체. –

+0

아마도 함수 밖에서'setTimeout'을 사용하거나'setInterval'을 사용하기를 원할 것입니다. – putvande

답변

0

아주 가깝고, 몇 가지.

당신은 모든 슬라이드 반복 그래서 루프를 종료 할 때,이 모든 슬라이드에 걸쳐 반복되는

function autoSlideshow() { 
    mySlides.each(function() { //code snipped } 
} 

는, 각각의 반복을 볼 수에 다음 슬라이드를 설정 그들 모두를 업데이트하고 ' 다시 시작한 곳으로 돌아 가세요.

당신은 새로운 타이머 당신이 기능

function autoSlideshow() { 
    //code snipped 
    setInterval(autoSlideshow, 3000); 
}; 

에게이 함수를 호출 할 때마다 호출 할 때마다 추가하고, 당신은 다시 호출하는 다른 타이머를 추가합니다. setInterval() 한 번만 사용하면됩니다. display: none;로 설정 클래스를 갖는

CSS 업데이트 해당 클래스 당신이 슬라이드를 업데이트 할 때마다 제거 할 필요합니다. 더 좋은 방법은 display: none;이 슬라이드 쇼의 이미지에 대한 기본값 인 속성이되도록하는 것입니다. 그런 다음 show 클래스를 추가하기 만하면되며 hide 클래스 제거에 대한 걱정은 없습니다.

업데이트 코드 :

자바 스크립트

$(document).ready(function() { //wait until the DOM is ready... 
    var mySlides = $('#slideshow .slide'); 
    var slides = []; 
    var index = 0; 

    mySlides.each(function() { 
    slides.push($(this)); 
    }); 

    function autoSlideshow() { 
    index++; 
    var nextSlide = index%slides.length; //the mod function makes sure you stay within the bounds of the array 
    $('.show').removeClass('show'); //remove the show class from the existing slide 
    slides[nextSlide].addClass('show'); //add the show class to the next slide 
    }; 
    setInterval(autoSlideshow, 3000); 
}) 

HTML

<section id="slideshow"> 
    <div class="auto-slideshow"> 
    <img src="https://unsplash.it/200/300" alt="" class="slide show"> 
    <img src="https://unsplash.it/200/301" alt="" class="slide"> 
    <img src="https://unsplash.it/200/302" alt="" class="slide"> 
    </div> 
</section> 

CSS

#slideshow img { display: none; } 
#slideshow img.show { display: block; } 

JS 피들에서 작동하는 것을보십시오 : https://jsfiddle.net/igor_9000/9mhujoa9/

희망이 있습니다!

0

제공된 HTML을 사용하면 slides 변수에 3 개의 요소가 있다고 가정 할 수 있습니다. 이제 mySlides를 반복 할 때 인덱스에 변수를 할당하고 해당 값 +1을 사용하여 slides 배열의 요소에 액세스합니다. 현재 mySlides 배열의 세 번째 항목에 있다면 어떻게됩니까? 색인은 2이고 다음은 3으로 설정됩니다. 슬라이드는 3 개의 값만 갖고 있으므로 슬라이드 [2]에만 도달 할 수 있으므로 코드는 현재 정의되지 않은 슬라이드 색인에 액세스하려고합니다.

1

먼저 mySlides를 정의한 후에 autoSlideshow()를 호출해야합니다. 다음으로 바운드 될 때 next의 값을 다시 초기화하십시오. autoSlideshow를 호출하는 가장 좋은 방법은 메소드에서 꺼내는 것입니다.

function autoSlideshow() { 
    var index; 
    var next; 

    mySlides.each(function() { 
     if ($(this).hasClass('show')) { 
      index = $(this).index(); 
      next = index + 1; 
      next = next >= mySlides.length ? 0 : next; 

      //DO WHAT YOU WERE DOING 
     }; 
    }); 

}; 

setInterval(autoSlideshow, 3000); 
+2

나는이 두 줄을'next = (index + 1) % mySlides.length; '와 같이 결합하는 것을 좋아한다. 이것은 자동으로 주위를 둘러싼 다. – Barmar

+0

네, 그게 더 좋은 방법입니다. –

0

아웃 바운드 인덱스를 가져 오기 때문에 오류가 발생합니다. 배열에 요소가 3 개 있고 인덱스가 0에서 시작하므로 array[3]은 범위를 벗어납니다.

그 외에도 $('#slideshow .slide')은 이미 요소 배열을 제공하므로 추가 배열을 정의 할 필요가 없습니다. 또한 함수 내에 setInterval을 사용하지 마십시오. 그러면 스크립트를 지우지 않고 스크립트를 반복 호출 할 때 스크립트가 충돌하게됩니다. 슬라이드 쇼 기능 안에서는 each으로 전화하지 마십시오. 한 번에 모든 슬라이드에서 업데이트가 수행됩니다. 당신이 원하는 것은 당신의 함수가 호출 될 때, 모든 슬라이드를 숨기고 현재 인덱스 만 보여줄 때입니다.

색인이 배열의 끝에 도달하면 처음부터 다시 0으로 재설정합니다.

.hide 클래스는 중복되는 것처럼 보입니다. 에 display: none을 추가하면됩니다. 이 같은

뭔가 할 것입니다 :

var mySlides = $('#slideshow .slide'); 
 
// whats the start index 
 
var slideIndex = $('#slideshow .show').index(); 
 
// how many slides 
 
var noOfSlides = mySlides.length; 
 

 
function autoSlideshow() { 
 
    // remove the 'show' class of all slides 
 
    mySlides.removeClass('show'); 
 

 
    // add 'show' class to only the slide with the slideIndex index 
 
    mySlides.eq(slideIndex).addClass('show'); 
 

 
    // update index 
 
    slideIndex++; 
 

 
    // restart at 0 
 
    if (slideIndex >= noOfSlides) 
 
    slideIndex = 0; 
 

 
}; 
 

 
autoSlideshow(); 
 
setInterval(autoSlideshow, 3000);
.slide { 
 
    display: none; 
 
} 
 
.show { 
 
    display: block; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<section id="slideshow"> 
 
    <div class="auto-slideshow"> 
 
    <img src="http://placehold.it/350x150/333" alt="" class="slide show"> 
 
    <img src="http://placehold.it/350x150/555" alt="" class="slide"> 
 
    <img src="http://placehold.it/350x150/111" alt="" class="slide"> 
 
    </div> 
 
</section>

관련 문제