• 카테고리

    질문 & 답변
  • 세부 분야

    웹 개발

  • 해결 여부

    미해결

인디케이터 업데이트에서 오류가 발생합니다.

20.08.31 15:03 작성 조회수 125

0

첫 이미지에서 오른쪽 클릭을 하면 인디케이터가 바뀌고 또 다시 클릭을 하면 에러가 발생하고 바뀌지 않습니다

에러는 Uncaught TypeError: Cannot set property 'className' of undefined

    at updateIndicator (carousel.js:66)

    at HTMLDivElement.<anonymous> (carousel.js:44)

입니다

작성한 코드는 

window.addEventListener('load', function () {
  let carousels = document.getElementsByClassName('carousel');
  //캐러셀 이벤트를 등록하는 로직
  for (let i = 0; i < carousels.length; i++{
    addEventToCarousel(carousels[i]);
  }
});

function addEventToCarousel(carouselElem){
  let ulElem = carouselElem.querySelector('ul');
  let liElems = ulElem.querySelectorAll('li');

  //너비 값 조정
  let liWidth = liElems[0].clientWidth;
  let adjustedWidth = liElems.length * liWidth;
  ulElem.style.width = adjustedWidth + 'px';

  //슬라이드 버튼 이벤트 등록
  let slideButtons = carouselElem.querySelectorAll('.slide');
  for (let i = 0; i < slideButtons.length; i++){
    slideButtons[i].addEventListener('click', createListenerSlide(carouselElem));
  }

}

function createListenerSlide(carouselElem){
  return function(e){
    let clickedButton = event.currentTarget;

    //값 가져오기
    let liElems = carouselElem.querySelectorAll('li');
    let liCount = liElems.length;
    let currentIndex = carouselElem.attributes.data.value;

    //슬라이드 버튼 체크
    if(clickedButton.className.includes('right'&& currentIndex < liCount - 1){
        currentIndex ++;
        scrollDiv(carouselElem, currentIndex);
    } else if (clickedButton.className.includes('left'&& currentIndex > 0){
        currentIndex --;
        scrollDiv(carouselElem, currentIndex);
    }
    //인디케이터 업데이트
    updateIndicator(carouselElem, currentIndex);
    //슬라이드 버튼 보여줌 여부 업데이트

    //새롭게 보여지는 이미지 인덱스 값을 현재 data 값으로 업데이트
    carouselElem.attributes.data.value = currentIndex;
  }
}

function scrollDiv(carouselElem, nextIndex) {
  let scrollable = carouselElem.querySelector('div');
  let liWidth = scrollable.clientWidth;
  let newLeft = liWidth * nextIndex;

  scrollable.scrollTo({left: newLeft, behavior: 'smooth'});
}

function updateIndicator(carouselElem, currentIndex){
  let indicators = carouselElem.querySelectorAll('footer > div');
  for (let i = 0; indicators.length; i++{
    if (currentIndex == i){
      indicators[i].className = 'active';
    } else {
      indicators[i].className = '';
    }
  }
}
여기까지 입니다

답변 1

답변을 작성해보세요.

0

for (let i = 0; indicators.length; i++{

이 부분에서 i < indicators를 뺴먹었네요,, 해결했습니당