通過jq實現分頁的原理如下:將所有條數加載到頁面中,根據每頁放特定條數(例如 5 條)獲取jquery對象索引,使部分條數顯示,其他條數隱藏。
前提:引入jquery.js
代碼

<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; list-style: none; } .wrapper{ width: 800px; margin: 50px auto; } /*清除浮動*/ .wrapper::after{ content: ""; display: block; clear: both; } ul li{ width: 100%; height: 30px; text-align: center; line-height: 30px; float: left; background: #ccc; margin: 10px 0px; } a{ cursor: pointer; border:1px solid black; } .btn{ float: right; } </style> <script type="text/javascript" src="jquery-3.1.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ /*添加100條數據(模仿后台傳入)*/ for(var i = 1; i<101;i++){ $("#content").append("<li>"+i+"</li>"); } /*設置每頁顯示的條數*/ $every_page = 5; $items = $("ul li"); $total_all = $items.length;//總條數 $page_num = Math.round($total_all/$every_page)//向上取整(2.5 ==> 3) $("#total_page").text($page_num); //初始化頁面,只顯示前5條。 $("ul li:gt("+($every_page-1)+")").each(function(){ $(this).hide(); }) //點擊下一條按鈕函數。 $("#next_page").click(function(){ $current_page = ($("#current_page").text());//獲取當前頁碼 if($current_page <$page_num){ $("#current_page").text(++$current_page); $.each($("ul li"),function(index,item){ //獲取下一頁顯示的開始索引。 var start = ($("#current_page").text()-1)*$every_page; if(index>=start&& index<start+$every_page){ $(this).show(); }else{ $(this).hide(); } }) }else{ return false; } }) $("#pre_page").click(function(){ $current_page = ($("#current_page").text()); if($current_page > 1){ $("#current_page").text(--$current_page); $.each($("ul li"),function(index,item){ var start = ($("#current_page").text()-1)*$every_page; if(index>=start&& index<start+$every_page){ $(this).show(); }else{ $(this).hide(); } }) }else{ return false; } }) }) </script> </head> <body> <div class="wrapper"> <div class="items"> <ul id= "content"> </ul> </div> <span class="btn"> <a id = "pre_page">上一頁</a> <span> <span id = "current_page">1</span> <span>/</span> <span id = "total_page"></span> </span> <a id = "next_page">下一頁</a> </span> </div> </body> </html>
運行結果