Javascript - 게시판 로직

위향훈·2023년 5월 28일
0
post-thumbnail
// 총 아이템 수
const totalItems = 100;

// 한 페이지에 표시할 아이템 수
const itemsPerPage = 10;

// 전체 페이지 수 계산
const totalPages = Math.ceil(totalItems / itemsPerPage);

// 현재 페이지
let currentPage = 1;

// 페이지네이션 컨테이너 엘리먼트 선택
const paginationContainer = document.querySelector('.pagination');

// 더미 데이터 생성 함수
function generateDummyData() {
  const dummyData = [];
  for (let i = 0; i < dummyData.length; i++) {
    dummyData.push(`Item ${i + 1}`);
  }
  return dummyData;
}

// 리스트 업데이트 함수 (현재 페이지에 맞게 아이템을 표시)
function updateList() {
  paginationContainer.innerHTML = '';

  // 더미 데이터 생성
  const dummyData = generateDummyData();

  // 현재 페이지에 해당하는 아이템 범위 계산
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentPageItems = dummyData.slice(startIndex, endIndex);

  // 현재 페이지 아이템 출력
  const listContainer = document.querySelector('.list-container');
  listContainer.innerHTML = '';

  currentPageItems.forEach((item) => {
    const listItem = document.createElement('li');
    listItem.textContent = item;
    listContainer.appendChild(listItem);
  });

  // 페이지네이션 생성
  createPagination();
}

// 페이지네이션 생성 함수
function createPagination() {
  // 이전 페이지 버튼 생성
  const prevButton = document.createElement('button');
  prevButton.textContent = '이전';
  prevButton.addEventListener('click', goToPreviousPage);
  paginationContainer.appendChild(prevButton);

  // 페이지 버튼 생성
  const startPage = Math.max(1, currentPage - 5);
  const endPage = Math.min(totalPages, startPage + 9);

  for (let i = startPage; i <= endPage; i++) {
    const pageButton = document.createElement('button');
    pageButton.textContent = i;
    pageButton.addEventListener('click', () => goToPage(i));
    paginationContainer.appendChild(pageButton);
  }

  // 다음 페이지 버튼 생성
  const nextButton = document.createElement('button');
  nextButton.textContent = '다음';
  nextButton.addEventListener('click', goToNextPage);
  paginationContainer.appendChild(nextButton);
}

// 이전 페이지로 이동
function goToPreviousPage() {
  if (currentPage > 1) {
    currentPage--;
    updateList();
  }
}

// 다음 페이지로 이동
function goToNextPage() {
  if (currentPage < totalPages) {
    currentPage++;
    updateList();
  }
}

// 특정 페이지로 이동
function goToPage(page) {
  currentPage = page;
  updateList();
}

// 초기 페이지네이션 및 리스트 업데이트
createPagination();
updateList();
profile
혼자 끄적여보는 필기 저장소 | 잠깐쓰고 잊지말고 기록하는 습관.

0개의 댓글