javascript - 如何创建动态分页
问题描述
我已经在 MVC 中完成了服务器端分页,但我无法动态显示数字和 Next 和 prev 链接按钮。请给我一些想法。
<nav aria-label="Page navigation example">
<ul class="pagination">
@for (int i = 1; i <= Model.PageCount; i++) // PageCount is Number of total Pages
{
<li class="page-item">
@if (i != Model.CurrentPageIndex) //Current Page say 1..2...3..etc
{
<a class="page-link" href="javascript:;" onclick="myClick(@i)">@i</a>
}
else
{
<span>@i</span>
}
</li>
}
</ul>
</nav>
我的问题是,如果我总共有 10 页(比如说)。我想在 Next 按钮中显示数字 1 到 5 的链接按钮。这样分页导航就会变成动态的。请帮助
解决方案
如果我理解正确,您担心的是您想限制生成的链接数量,以便用户看到的不是从 1 开始到 结束的每个页面的链接,而是PageCount
只看到一个完整链接列表的范围。
这里的想法是引入另一个参数,称为它numbersToShow
,它表示您要呈现的链接总数。
例如,当有 10 个页面时,链接的总数可能是 5 个。
计算此子集的开始和结束索引的示例函数可能如下所示:
static (int min, int max) GetPagingRange( int currentPage, int totalPages, int numbersToShow = 5 )
{
if ( currentPage < 1 || totalPages < 1 || currentPage > totalPages ) throw new ArgumentException();
if ( numbersToShow < 1 ) throw new ArgumentException();
var min = Math.Max(1, currentPage - numbersToShow/2);
var max = Math.Min(totalPages, currentPage + numbersToShow/2 + Math.Max( 0, min - currentPage + numbersToShow/2 ) );
return (min, max);
}
这里发生的是我们从当前页面开始并尝试使其位于动态范围的中间(因此我们numbersToShow/2
向左和向右)。两者都Math.Min
确保Math.Max
我们保持在有效范围内。
计算时还有另一个组件会在max
渲染前几页时尝试补偿范围左侧部分的不足。
考虑这个示例用法,它显示了返回的范围值:
Console.WriteLine( "Total pages: 10" );
Console.WriteLine( "Numers to show: 5" );
int totalPages = 10;
for ( int currentPage = 1; currentPage <= totalPages; currentPage++ )
{
var result = GetPagingRange( currentPage, totalPages );
Console.WriteLine( $"CurrentPage: {currentPage}, starting page index: {result.min} ending page index: {result.max}");
}
这里的输出是
Total pages: 10
Numers to show: 5
CurrentPage: 1, starting page index: 1 ending page index: 5
CurrentPage: 2, starting page index: 1 ending page index: 5
CurrentPage: 3, starting page index: 1 ending page index: 5
CurrentPage: 4, starting page index: 2 ending page index: 6
CurrentPage: 5, starting page index: 3 ending page index: 7
CurrentPage: 6, starting page index: 4 ending page index: 8
CurrentPage: 7, starting page index: 5 ending page index: 9
CurrentPage: 8, starting page index: 6 ending page index: 10
CurrentPage: 9, starting page index: 7 ending page index: 10
CurrentPage: 10, starting page index: 8 ending page index: 10
请注意,虽然补偿适用于起始页(例如,当当前页为 1 时,范围是 1 到 5),但在呈现少数最后一页时(例如,在最后 10 页,范围是 8 到 10)没有补偿。这可能会得到改进,或者您可以保持原样。
该代码也可在fiddle中找到。
推荐阅读
- python - Python遍历字典列表
- java - Spring Integration 如何从多个 ftp 服务器和目录中获取文件?
- exception - While 循环使用 ESPNOW 引发异常
- java - 基于 Gradle 的子项目在构建过程中抛出`Could not find or load main class worker.org.gradle.process.internal.worker.GradleWorkerMain`
- c# - 需要使用 C# 在现有 XML 文件下添加新项目
- powershell - Powershell 脚本分析 MFA
- excel - 使用 VBA 创建 Excel 元数据以在 sharepoint 中进行筛选
- java - JUNIT 在 quarkus 中运行测试用例时不使用 src/test/resources
- laravel - Laravel 迁移与人员/人员表名混合
- python - 如何搜索目录中的图像并将它们保存到另一个文件夹中?