章節連結
網頁設計中常見的分頁功能(Pagination)的實作筆記過程。邏輯上,可以拆解成以下兩項:
1.計算總共頁數
2.依照使用者點擊的頁數來決定顯示多少項目
實作步驟
1.HTML部分
1 2 3 4 5 6 7 8 |
<!--採用 Bootstrap 4.0 --> <nav aria-label="Page navigation"> <ul class="pagination justify-content-center" id="pagination"> <li class="page-item"> <a class="page-link" href="#">1</a> </li> </ul> </nav> |
2.JavaScript部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
//pagination 監聽器 pagination.addEventListener('click', event => { event.preventDefault() if (event.target.tagName === 'A') { getPageData(event.target.dataset.page) } }) //計算總共頁數 function getTotalPages(choiceMovies) { let totalPages = Math.ceil(choiceMovies.length / ITEM_PER_PAGE) || 1 let pageItemContent = '' for (let i = 0; i < totalPages; i++) { pageItemContent += ` <li class="page-item"> <a class="page-link" href="javascript:;" data-page="${i + 1}">${i + 1}</a> </li> ` } pagination.innerHTML = pageItemContent } //篩選出指定頁面的資料並顯示 function getPageData(pageNum, choiceMovies) { dataPanel.innerHTML = '' //記得先清空現有內容 paginationData = choiceMovies || paginationData let offset = (pageNum - 1) * ITEM_PER_PAGE let pageData = paginationData.slice(offset, offset + ITEM_PER_PAGE) let htmlContent = '' //console.log(paginationData) if (paginationData.length === 0) { dataPanel.innerHTML = ` <h3>此類別無資料,請點選其他選項。</h3> ` } for (let i = 0; i < pageData.length; i++) { htmlContent += ` <div class="col-sm-4"> <div class="card mb-1"> <img class="card-img-top " src="${posterBASE_URL}${pageData[i].image}" alt="Card image cap"> <div class="card-body movie-item-body"> <h5 class="card-title">${pageData[i].title}</h5> ` for (let j = 0; j < pageData[i].genres.length; j++) { htmlContent += ` <h6><span class="badge badge-secondary">${genresList[pageData[i].genres[j]]}</span></h6> ` } htmlContent += ` </div> </div> </div> ` //console.log(htmlContent) } dataPanel.innerHTML += htmlContent } |
參考資料
本篇主要參考自 AlphaCamp 的實戰學期二課程內容,詳情可上這裡觀看。此篇並無業配與其他利益往來,只是課堂內的實作經驗分享。
按讚加入粉絲團