简体   繁体   中英

Js pagination page links don't work

I'm trying to implement a simple pagination project while I got stuck with a search bar issue.

Here's what I've accomplished so far:

  • 10 entries are displayed per one page
  • my script can calculate the total number of page links based on total number of entries(students)
  • I can visit every single page and see its entries (say, page 1: students from 0 to 9... page 3: students from 30 to 39, etc)
  • The search function
  • I deliberately turned off a search by button. It's only available with 'keyup' event listener.

What I failed to implement so far:

When typing a search query: '/15', 2 pages are displayed with according entries. But then if I click on page 2 link, it displays more than 10entries per page(default parameter) and going back to page 1 the same error occurs. I suspect the page links get a wrong value from somewhere else. I tried to debug and it seems as if they're getting the value from $studentList(the whole list of students) but not from the search results that I pass there.

In all, I have 3 functions

function showPage(studentList, pageNum = 1){
  const showPerPage = 10;    
  $(studentList).hide(); 
  const calcStart = (pageNum) => pageNum === 1 ? 0 : (pageNum - 1) * showPerPage;
  const start = calcStart(pageNum);
  const end = pageNum * showPerPage;
  $(studentList).slice(start,end).each(function(i, li){
    $(li).fadeIn(50);
});
}

  function appendPageLinks(studentList){
    totalPageNum = Math.ceil(studentList.length / 10);
    const pagination = 'pagination';
    if($('.pagination').length === 0){
        $('.page').append(`
        <div class="${pagination}">
            <ul></ul>
        </div>
    `);
    } 
    $('.pagination ul').children().remove();
    if (totalPageNum > 1){
        for(let i=0; i<totalPageNum; i++){
            const pageLink = `
                <li>
                    <a href="#">${i + 1}</a>
                </li>
            `;
            $('.pagination ul').append(pageLink);
        }
    }
    $('.pagination ul li').children().first().addClass('active'); 
        $('.pagination ul').on('click', 'a', function(e){
            e.preventDefault();
            const pgNum = parseInt($(e.target).text());
            showPage(studentList, pgNum);
            $(this).parent().siblings().children().removeClass('active');
            $(this).addClass('active');
        });
    } 


function searchStudent(element, filter){
$(element).each(function(){         
    if($(this).text().toUpperCase().includes(filter)){
        $(this).show();
    } else {
        $(this).hide();
    }        
});
let num = $('.student-item:not([style*="display: none"])').length;
let searchRes = $('.student-item:not([style*="display: none"])');
num > 0 ? $('.notFound').hide() : $('.notFound').show();
return searchRes;
}

I think that these event listeners aren't getting the proper values:

$('.student-search input').on('keyup', function(){
const searchQuery = $(this).val();
const searchResults = searchStudent($('.student-list li'), searchQuery.toUpperCase());
showPage(searchResults);
appendPageLinks(searchResults);

});

As well as this one above

 $('.pagination ul').on('click', 'a', function(e)

Here's a source code on codepen: https://codepen.io/hopper86/pen/WJmMMG?editors=1010

If someone could suggest how to fix to have the page links updated properly.

 $('.pagination ul').on('click', 'a', function(e){
        e.preventDefault();
        const pgNum = parseInt($(e.target).text());
        showPage(studentList, pgNum);
        $(this).parent().siblings().children().removeClass('active');
        $(this).addClass('active');
    });

The problem is with the above function( showPage(studentList, pgNum); ). While you click on the pagination links the whole student array is being passed as the studentList. Instead you might want to send only the result that you get after your search query has given you a new studentArray.

below is the js that i have made some changes to, might get you the result you want.

// Setting up variables
const $studentList = $('.student-list').children();
var $changedStudentList = $studentList;
$('.student-list').prepend('<div class="notFound"></div>');
$('.notFound').html(`<span>No results</span>`);
$('.notFound').hide();

// Bulding a list of ten students and displaying them on the page
function showPage(studentList, pageNum = 1){
    const showPerPage = 10;    
    // hide all students on the page
    $(studentList).hide(); 

    // Get start/end for each student based on the page number
    const calcStart = (pageNum) => pageNum === 1 ? 0 : (pageNum - 1) * showPerPage;
    const start = calcStart(pageNum);
    const end = pageNum * showPerPage;

// Looping through all students in studentList
$(studentList).slice(start,end).each(function(i, li){
    // if student should be on this page number
    // show the student
    $(li).fadeIn(50);
});
}

// Search component
const searchBar = `
<div class="student-search">
    <input placeholder="Search for students...">
    <button>Search</button>
</div>
`;
$('.page-header').append(searchBar);

$('.student-search input').on('keyup', function(){
const searchQuery = $(this).val();
const searchResults = searchStudent($('.student-list li'), searchQuery.toUpperCase());
$changedStudentList = searchResults;
showPage(searchResults);
appendPageLinks(searchResults);
});


// Student search
function searchStudent(element, filter){

$(element).each(function(){         
    if($(this).text().toUpperCase().includes(filter)){
        $(this).show();
    } else {
        $(this).hide();
    }        
});
let num = $('.student-item:not([style*="display: none"])').length;
let searchRes = $('.student-item:not([style*="display: none"])');
num > 0 ? $('.notFound').hide() : $('.notFound').show();
return searchRes;
};



// Creating all page links based on a list of students
function appendPageLinks(studentList){
// determine how many pages for this student list
totalPageNum = Math.ceil(studentList.length / 10);
// create a page link section
const pagination = 'pagination';
// add a page link to the page link section
// if class the element already exists
if($('.pagination').length === 0){
    $('.page').append(`
    <div class="${pagination}">
        <ul></ul>
    </div>
`);
} 

// remove the old page link section from the site
$('.pagination ul').children().remove();

if (totalPageNum > 1){
    // 'for' every page
    for(let i=0; i<totalPageNum; i++){
        const pageLink = `
            <li>
                <a href="#">${i + 1}</a>
            </li>
        `;
        // append our new page link section to the site
        $('.pagination ul').append(pageLink);
    }
}

$('.pagination ul li').children().first().addClass('active'); 

    // define what happens when you click a link (event listener)
    $('.pagination ul').on('click', 'a', function(e){
        e.preventDefault();
        const pgNum = parseInt($(e.target).text());
        // Use showPage() to display the page for the link clicked
        showPage($changedStudentList, pgNum);
        // mark that link as 'active'
        $(this).parent().siblings().children().removeClass('active');
        $(this).addClass('active');
    });
} 

showPage($studentList);
appendPageLinks($studentList);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM