Как исправить ошибку Pagination «Кнопки отображаются только на первой и последней странице, но ни одна из страниц между ними»? - PullRequest
0 голосов
/ 09 января 2019

Я пытаюсь разбить список элементов ученика на разные страницы. Кнопки добавляются только к первой странице и последней странице. Я также хотел бы добавить элементы кнопки на страницы со 2 по 5. В моем коде ошибка или отсутствует элемент?

Мы рассмотрели все циклы for, чтобы выяснить, есть ли проблема с параметрами. Мы также попытались изменить типы переменных.

/******************************************
Treehouse Techdegree:
FSJS project 2 - List Filter and Pagination
******************************************/

// Study guide for this project - https://drive.google.com/file/d/1OD1diUsTMdpfMDv677TfL1xO2CEkykSz/view?usp=sharing
/***
   Add your global variables that store the DOM elements you will
   need to reference and/or manipulate.
***/

//Step 2: Get the elements for students and for pagination and page
// Grabs all the li Item and stores them into StudentListItem
let StudentListItem = document.getElementsByTagName('li'); 

console.log(StudentListItem.length);

//Takes the children of the li Item and stores them into ChildListItem. Aka the ul Item
let ChildListItem = StudentListItem.children;

//Makes the child item so you manipulate the elements in the DOM

let NumberofItem = StudentListItem.length;

//Step 3 & 4: Determine the number of elements that goes on one page. And 
// create the variable for the number of pages needed

const ItemPerPage = 10;

//Step 5: Create a function that determines the number of pages PagesNeeded
const TotalPages = Math.ceil(StudentListItem.length/ItemPerPage);

//Step 6: Create for- loop that deletes the display for all the items
for (var i = 0; i < StudentListItem.length; i++) {
  StudentListItem[i].style.display = 'none';
}

//Step 7: Create a function that only shows the first ten list items.
function showPage (page, ChildListItem) {
  // Loops through items to find what to hide or show
  for (let i = 0; i < StudentListItem.length; i++) {
    // shows the first 10 items in list
    if (i < (page * ItemPerPage) && i >= ((page * ItemPerPage) - ItemPerPage)) {
      StudentListItem[i].style.display = 'block';
    } else {
      // hides the rest of the 
      StudentListItem[i].style.display = 'none';items
    }
  }
};

showPage(1,ChildListItem);


// Loop to create page buttons based on number of required pages
const buttonDiv = document.createElement('div'); // creates a div for buttons
const mainPage = document.querySelector('.page'); // creating a selector for page div

console.log(mainPage);

mainPage.appendChild(buttonDiv); // appends buttonsdiv to the page
buttonDiv.className = 'pagination'; // gives buttodiv the class name pagination
console.log(buttonDiv); // logs button div to  console

const buttonUl = document.createElement('ul'); // creating unordered list
buttonDiv.appendChild(buttonUl); //append list to buttondiv


for (let i = 0; i < TotalPages; i+= 1) { // for-loop creates li and a element.
  pageli = document.createElement('li');
  const pageLink = document.createElement('a'); // a makes the buttons hyperlinks
  pageLink.className = 'active'; // activates the a link created by a variable
  pageLink.href = '#'; //puts numbers as the hyperlink text
  pageLink.textContent = i + 1; //textcontent i + 1
  pageli.appendChild(pageLink); //appends the pagelinks
  buttonUl.appendChild(pageli); // appends the buttonul to the li

  //The page = a notebook
  //The ul = pages in a notebook
  //The li = writing on the page in the notebook
  // -------------------PAGE------------------
  //            ---------UL----------
  //                  ---LI--------

  buttonDiv.addEventListener('click', (event) => {
      let buttonNumber = parseInt(event.target.textContent);
      let max = buttonNumber * 10;
      let min = max - 10;
      for (let i = 0; i < StudentListItem.length; i++) {
          if (i >= min && i < max) {
              StudentListItem[i].style.display = '';
          }  else {
              StudentListItem[i].style.display = 'none';
          }
      }
  });//evernt listener

}

console.log(buttonUl);
console.log(TotalPages);

Ссылка GitHub в реальном времени здесь .

Я ожидаю, что все элементы кнопки будут добавлены на страницах 1-6.

1 Ответ

0 голосов
/ 08 июля 2019

Проблема здесь в том, что document.getElementsByTagName("li") возвращает live NodeList. См. MDN .

Живой NodeList будет обновляться при добавлении в документ дополнительных элементов li. В этом случае, когда элементы пагинации li добавляются в документ, они скрываются вместе со всеми другими элементами, отсутствующими на текущей странице. При нажатии кнопки нумерации страниц.


Чтобы продемонстрировать это, я покажу ваш код (Аннотации мои) :

let StudentListItem = document.getElementsByTagName('li'); // a live list
console.log(StudentListItem.length); // <-- 54 in your GitHub example
// ...
// Now create the pagination buttons:
for (let i = 0; i < TotalPages; i+= 1) {
  pageli = document.createElement('li');    // <-- Here we create a new li in the document
  const pageLink = document.createElement('a');
  pageLink.className = 'active';
  pageLink.href = '#';
  pageLink.textContent = i + 1;
  pageli.appendChild(pageLink);
  buttonUl.appendChild(pageli);

  // ...
  // add the event listener
} // End of loop for each pagination button

Так что теперь, если вы проверите StudentListItem, вы обнаружите, что теперь он содержит больше элементов. (Это список live , помните)

console.log(StudentListItem.length); // <-- now 60 (54 original plus 6 from the pagination links)

Решение:

Решение состоит в том, чтобы не иметь StudentListItem быть списком live для всех элементов li в document.

Я думал о трех возможных решениях:

  1. Не получить все пунктов списка, ограничить его только оригинальным ul.

    Например:

    let ul = document.getElementsByTagName("ul");
    let StudentListItem = ul.getElementsByTagName("li");
    

    Теперь это все еще живой список, но нумерация страниц li не является дочерними для ul, который мы выбираем.

  2. Не используйте live список.

    let StudentListItem = document.querySelectorAll("li");
    

    Здесь document.querySelectorAll возвращает статический список, который не будет обновляться при добавлении новых элементов li в document.

  3. Просто используйте заранее рассчитанную длину при скрытии предметов. (NumberofItem) Так что вместо

    for (let i = 0; i < StudentListItem.length; i++) {
         // Hide items...
    

    сделать

    for (let i = 0; i < NumberofItem; i++) {
    

    Это ограничивает количество скрытых li элементов только оригинальными.


Еще одна вещь, которую я заметил, это то, что слушатель событий был прикреплен к контейнеру вокруг кнопок разбиения на страницы, а не к самим кнопкам. Это можно исправить, заменив

buttonDiv.addEventListener('click', (event) => {

с

pageli.addEventListener('click', (event) => {

Причина, по которой кнопки отображаются на первой странице, заключается в том, что они не были скрыты, чтобы скрыться при вызове первой функции showPage(). Причина, по которой кнопки отображаются на странице 6 th , заключается в том, что они представляют собой элементы 55-60 th li, которые попадают в элементы 6 th стр.

...