jQuery 分頁插件

實現以下效果的分頁插件javascript

css 代碼css

.pre:hover, .next:hover, .pagenum:hover{
    background: #ccc;
}
.pre, .next, .pagenum{
    float:left;
    background:white;
    cursor:pointer;
    text-align: center;
    line-height:38px;
    margin:0 3px;
    height:38px;
    width:38px;
    display:block;
    border:1px solid #95B8E7}
.active{
    background: #95B8E7 !important;
    cursor:not-allowed;
}

js 代碼html

(function($) {
    var defaults = {
        pages: 1,   // 請求頁碼
	currentPage: 1, // 當前頁碼
	rows:10, // 請求條數
	url: '', // 後臺 URL
	queryParams:{}, // 請求額外參數
	loadFun: function(res){return res;} // 請求成功後執行函數
    };
    
    var _self, param, opt;

    $.fn.jpage = function (options) {
    	param = $.extend({}, options.queryParams);
        opt = $.extend({}, defaults, options);
    	_self = this;
        // 發送請求
	getRows();
    }

    // 頁碼顯示
    function setPages(dom, opt){
    	$(dom).html('');
        $(dom).append("<span title='上一頁' class='pre'>&lt;</span>");
        // 顯示5個頁碼 
        if(opt.currentPage > 5){
            for(var i=opt.currentPage-4; i<opt.currentPage+1; i++){
	        $(dom).append("<span class='pagenum' data-id='"+ i +"'>"+ i +"</span>");
	    }
        }else{
            for(var i=1; i<opt.pages+1; i++){
	        $(dom).append("<span class='pagenum' data-id='"+ i +"'>"+ i +"</span>");
	    }
        }
        $(dom).append("<span title='下一頁' class='next'>&gt;</span>");
        $(dom).append("<span style='position:relative;top:16px;clear:both'> 共 "+opt.pages+" 頁</span>");

        // 當前頁設置
        $(dom).children(".pagenum[data-id='"+opt.currentPage+"']").addClass("active");
    }

    // 頁碼,上下頁點擊事件
    function pageJump(dom, options){
    	$(".pagenum").click(function(){
    	    if(!$(this).hasClass('active')){
    		var pagenum = parseInt($(this).text());
	    	opt.currentPage = pagenum;
	    	// 發送請求
		getRows();
    	    }
	});
    	$(".pre").one("click", function(){
    	    var pagenum = parseInt($(".active").text())-1;
    	    if(0 != pagenum){
    		opt.currentPage = pagenum;
	    	// 發送請求
		getRows();
    	    }
    	});
    	$(".next").one("click", function(){
    	    var pagenum = parseInt($(".active").text())+1;
    	    if(pagenum <= opt.pages){
    		opt.currentPage = pagenum;
	    	// 發送請求
		getRows();
    	    }
    	});
    }

    // 數據請求
    function getRows(){
    	$.post(opt.url, {rows:opt.rows,page:opt.currentPage,filterRules: param}, function(res){
	    opt.loadFun(res);
	    opt.pages = Math.ceil(parseInt(res.total)/opt.rows);
	    setPages(_self, opt);
	    pageJump(_self, param);
	}, "json");
    }
})(jQuery);

後臺傳送數據格式java

{total: 13, rows: []}json

js 調用app

$('.pagebox').jpage({
	url:"", // 後臺路徑
	queryParams:{}, // 請求的額外參數
	loadFun: function(res){} // 請求成功執行函數,可設置 html 內容
});
相關文章
相關標籤/搜索