我是JavaScript的新手,如果这是显而易见的或者问题不清楚,我深表歉意。
我有一个分页作业,我必须使用一个函数将学生列表限制在每页10个。我被允许使用一些jQuery,但绝对不允许使用插件。
目前我有:
const numberOfStudents = $('.page .student-item').length;
const limitPerPage = 10;
var totalPages = Math.ceil(numberOfStudents / limitPerPage);
我如何使用它创建一个函数呢?限制学生的数量。我在考虑使用循环,但我不知道从哪里开始。
提前感谢!
发布于 2018-09-20 05:54:15
不久前,我写了这个小函数来为我处理分页数组。您不应该在非常大的数组上使用它,但对于相对较小的数组,它可以完成这项工作。它的用法应该是不言自明的:
function paginateArray(ary, perPage=10, pageNumber=1) {
const start = perPage * (pageNumber - 1)
const size = ary.length
return {
data: ary.slice(start, start + perPage),
numberOfPages: Math.ceil(size / perPage),
currentPage: pageNumber,
dataLength: size
}
}
paginateArray([1,2,3,4,5], 2, 1]
// {data: [1, 2], numberOfPages: 3, currentPage: 1, dataLength: 5}
发布于 2018-09-20 06:15:59
对DOM元素已经加载到页面上的.student-item
进行分页的赋值吗?这不是标准的,但如果这就是任务,那么我建议隐藏不在“当前页面”上的.student-item
。
// All this code should run after the .student-item's are loaded.
// If this makes for an ugly flash of .student-item's that should not
// be shown, then you can hide the .student-item's by default in css,
// and let jquery force the .student-item to be shown.
function displayPage(pageNum) { // pageNum must be between 0 and totalPages-1
$('.page .student-item').each(function(idx, studentEle) {
if (idx >= (limitPerPage * pageNum) && idx < (limitPerPage * (pageNum+1))) {
studentEle.show(); // student is on this page
} else {
studentEle.hide(); // student is NOT on this page
}
});
}
$('.page-select').on('change', function () {
// example <select> element for the page.
// Most likely you would want some links or buttons, not a <select> element, but this is just an example
var selectedPage = $('.page-select option:selected').first().val();
displayPage(selectedPage - 1);
});
displayPage(0);
发布于 2018-09-20 06:22:14
看起来您是在使用jQuery来操作DOM,实际上可能并没有数据可供您直接使用。从专业的角度来看,这段代码不是最好的解决方案,但我认为它符合您的教育情况。
var currentPage = 1;
// Hide every student beyond the first page
$('.student-item').each(function(i, student) {
if (i >= limitPerPage * currentPage) {
$(student).hide()
}
});
// Manipulate the DOM to show the students on the new 'page'
function displayNewPage() {
$('.student-item').each(function(i, student) {
if (i >= limitPerPage * currentPage || i < limitPerPage * (currentPage - 1)) {
$(student).hide();
} else {
$(student).show();
}
});
};
// Create a button with id 'page-left' for this work
$('#page-left').on('click', function() {
if (currentPage > 1) {
currentPage--;
displayNewPage();
}
if (currentPage === 1) {
$('#page-left').prop('disabled', true);
}
$('#page-right').prop('disabled', false);
});
// Create a button with id 'page-right' for this work
$('#page-right').on('click', function() {
if (currentPage < totalPages) {
currentPage++;
displayNewPage();
}
if (currentPage === totalPages) {
$(event.target).prop('disabled', true);
}
// Allow
$('#page-left').prop('disabled', false);
});
https://stackoverflow.com/questions/52414471
复制相似问题