定义三个文件:demo1.html/demo1.js/demo1.css 还有引入jQuery库:jquery-3.2.1.js
1. demo1.html
分页插件
2. demo1.js
(function () { //默认值 var curPage = 1; var showN = 5; var total = 20; //给jQuery对象的原型添加方法 jQuery.fn.pageInit = function (curPTemp,showNTemp,totalPTemp) { curPage = curPTemp; showN = showNTemp; total = totalPTemp; callback(); }; //回调函数 function callback() { //根据初始化获取的参数进行制作UI var str = ''; for(var i=0;i" +(curpage+i).tostring()+'< a> '; } str = ' 上一页 ' + str + '下一页 '; var page = '' + str +'
'; $('#pageDiv').html(page); //第一次起来当前的页在最左边,高亮。 $("#pageDiv a").eq(1).css("background-color", "green"); $('#pageShow').text(curPage.toString()); //给页码添加点击的监听函数 $('#pageDiv a').click(function () { var temp = $(this).text(); //直接点击一个页码的操作 if(temp !== '下一页' && temp!== '上一页' ){ $('#pageDiv a').css("background-color","darkblue"); $(this).css("background-color","green"); $('#pageShow').text(temp); curPage = parseInt(temp); } //上一页的操作 if(temp === '上一页') { if (curPage == 1 ) { $('#pageShow').text("首页"); }else { if (curPage <= parseInt($("#pageDiv a").eq(1).text())) { $("#pageDiv a").each(function () { var temp = $(this).text(); if (temp !== '下一页' && temp !== '上一页') { $(this).text((parseInt(temp)-1).toString()); } }); curPage = parseInt($("#pageDiv a").eq(1).text()); console.log("\n " + curPage); $('#pageShow').text(curPage.toString()); } else { $("#pageDiv a").each(function () { if ((curPage - 1).toString() === $(this).text()) { $('#pageDiv a').css("background-color", "darkblue"); $(this).css("background-color", "green"); } }); curPage -= 1; $('#pageShow').text(curPage.toString()); } } } //下一页的操作 if(temp === '下一页') { if (curPage >= total) { $('#pageShow').text("末页"); } else { if (parseInt($("#pageDiv a").eq(-2).text()) <= curPage) { $("#pageDiv a").each(function () { var temp = $(this).text(); if (temp !== '下一页' && temp !== '上一页') { $(this).text((parseInt(temp) + 1).toString()); } curPage = parseInt($("#pageDiv a").eq(-2).text()); $('#pageShow').text(curPage.toString()); }); }else { $("#pageDiv a").each(function () { if ((curPage + 1).toString() === $(this).text()) { $('#pageDiv a').css("background-color", "darkblue"); $(this).css("background-color", "green"); } }); curPage += 1; $('#pageShow').text(curPage.toString()); } } } }); }}());
3. demo1.css
#pageDiv a,#pageDiv li{ float: left; height: 30px; width: 90px; list-style: none; border-style: solid; text-align: center; color: white; background-color: darkblue; text-decoration:none;}#pageShow{ text-align: center; height: 400px; font-size: 15em;}#pageDiv{ text-align: center; background-color: yellow; clear: both; margin-left: 300px;}