您的位置:首页 > Web前端 > JQuery

扩展jquery.pagination支持Ajax及带参数请求

2010-07-20 09:10 501 查看
由于项目需要,扩展了Jquery 的Pagination。使得jquery.pagination,可能直接带参数Ajax请求服务器并更新对应容器的内容。

记录下来:

 

原文地址:http://blog.csdn.net/Vange/archive/2010/07/20/5748477.aspx

===============================================

使用方法:

相关的JQuery库及CSS请自行下载。

demo_vange.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pagination Demo I - Simple pagination</title>
<link rel="stylesheet" href="../pagination.css" mce_href="pagination.css" />
<link rel="stylesheet" href="demo.css" mce_href="demo.css" />
<mce:script type="text/javascript" src="lib/jquery.min.js" mce_src="lib/jquery.min.js"></mce:script>
<mce:script type="text/javascript" src="../jquery.pagination.js" mce_src="jquery.pagination.js"></mce:script>

<mce:script type="text/javascript"><!--

// This is a very simple demo that shows how a range of elements can
// be paginated.
// The elements that will be displayed are in a hidden DIV and are
// cloned for display. The elements are static, there are no Ajax
// calls involved.

/**
* Callback function that displays the content.
*
* Gets called every time the user clicks on a pagination link.
*
* @param {int} page_index New Page index
* @param {jQuery} jq the container with the pagination links as a jQuery object
*/
function pageselectCallback(page_index, jq){
var new_content = jQuery('#hiddenresult div.result:eq('+page_index+')').clone();
$('#Searchresult').empty().append(new_content);
return false;
}

/**
* Initialisation function for pagination
*/
function initPagination() {
// count entries inside the hidden content
//var num_entries = jQuery('#hiddenresult div.result').length;
var num_entries =  100;
// Create content inside pagination element
$("#Pagination").pagination(num_entries, {
//callback: pageselectCallback,
items_per_page:1, // Show only one item per page
url:"snippet.html",
params:{"pageSize":3, "condition1":"value1"},
showResultContainer:"Searchresult"
});
}

// When document is ready, initialize pagination
$(document).ready(function(){
initPagination();
});

// --></mce:script>
</head>
<body>
<h1>jQuery Pagination Plugin Demo</h1>
<div id="Pagination"></div>
<br style="clear:both;" mce_style="clear:both;" />
<div id="Searchresult">
This content will be replaced when pagination inits.
</div>

<!-- Container element for all the Elements that are to be paginated -->
<div id="hiddenresult" style="display:none;" mce_style="display:none;">
<div class="result"><p>Globally maximize granular
"outside the box" thinking vis-a-vis quality niches. Proactively formulate 24/7
results whereas 2.0 catalysts for change. Professionally implement 24/365 niches
rather than client-focused users.</p>
<p>
Competently engineer high-payoff "outside the box" thinking through cross
functional benefits. Proactively transition intermandated processes through
open-source niches. Progressively engage maintainable innovation and extensible
interfaces.</p>
</div>
<div class="result"><p>Credibly fabricate e-business models for end-to-end niches.
Compellingly disseminate integrated e-markets without ubiquitous services.
Credibly create equity invested channels with multidisciplinary human capital.</p>
<p>
Interactively integrate competitive users rather than fully tested
infomediaries. Seamlessly initiate premium functionalities rather than impactful
architectures. Rapidiously leverage existing resource-leveling processes via
user-centric portals.</p>
</div>
<div class="result"><p>Monotonectally initiate unique
e-services vis-a-vis client-centric deliverables. Quickly impact parallel
opportunities with B2B bandwidth. Synergistically streamline client-focused
infrastructures rather than B2C e-commerce.</p>
<p>
Phosfluorescently fabricate 24/365 e-business through 24/365 total linkage.
Completely facilitate high-quality systems without stand-alone strategic theme
areas.</p>
</div>
</div>

<div id="footer">
Copyright © 2010 by <a href="http://www.d-scribe.de/" mce_href="http://www.d-scribe.de/">describe europe Ltd.</a>.
</div>
</body>
</html>


 

===============================================

修改后的Jquery 的Pagination:jquery.pagination.js

/**
* This jQuery plugin displays pagination links inside the selected elements.
*
* This plugin needs at least jQuery 1.4.2
*
* @author Gabriel Birke (birke *at* d-scribe *dot* de)
* @version 2.0rc
* @param {int} maxentries Number of entries to paginate
* @param {Object} opts Several options (see README for documentation)
* @return {Object} jQuery Object
*/
(function($){
/**
* @class Class for calculating pagination values
*/
$.PaginationCalculator = function(maxentries, opts) {
this.maxentries = maxentries;
this.opts = opts;
}

$.extend($.PaginationCalculator.prototype, {
/**
* Calculate the maximum number of pages
* @method
* @returns {Number}
*/
numPages:function() {
return Math.ceil(this.maxentries/this.opts.items_per_page);
},
/**
* Calculate start and end point of pagination links depending on
* current_page and num_display_entries.
* @returns {Array}
*/
getInterval:function(current_page)  {
var ne_half = Math.ceil(this.opts.num_display_entries/2);
var np = this.numPages();
var upper_limit = np - this.opts.num_display_entries;
var start = current_page > ne_half ? Math.max( Math.min(current_page - ne_half, upper_limit), 0 ) : 0;
var end = current_page > ne_half?Math.min(current_page+ne_half, np):Math.min(this.opts.num_display_entries, np);
return {start:start, end:end};
}
});

// Initialize jQuery object container for pagination renderers
$.PaginationRenderers = {}

/**
* @class Default renderer for rendering pagination links
*/
$.PaginationRenderers.defaultRenderer = function(maxentries, opts) {
this.maxentries = maxentries;
this.opts = opts;
this.pc = new $.PaginationCalculator(maxentries, opts);
}
$.extend($.PaginationRenderers.defaultRenderer.prototype, {
/**
* Helper function for generating a single link (or a span tag if it's the current page)
* @param {Number} page_id The page id for the new item
* @param {Number} current_page
* @param {Object} appendopts Options for the new item: text and classes
* @returns {jQuery} jQuery object containing the link
*/
createLink:function(page_id, current_page, appendopts){
var lnk, np = this.pc.numPages();
page_id = page_id<0?0:(page_id<np?page_id:np-1); // Normalize page id to sane value
appendopts = $.extend({text:page_id+1, classes:""}, appendopts||{});
if(page_id == current_page){
lnk = $("<span class='current'>" + appendopts.text + "</span>");
}
else
{
lnk = $("<a>" + appendopts.text + "</a>")
.attr('href', this.opts.link_to.replace(/__id__/,page_id));
}
if(appendopts.classes){ lnk.addClass(appendopts.classes); }
lnk.data('page_id', page_id);
return lnk;
},
// Generate a range of numeric links
appendRange:function(container, current_page, start, end) {
var i;
for(i=start; i<end; i++) {
this.createLink(i, current_page).appendTo(container);
}
},
getLinks:function(current_page, eventHandler) {
var begin, end,
interval = this.pc.getInterval(current_page),
np = this.pc.numPages(),
fragment = $("<div class='pagination'></div>");

// Generate "Previous"-Link
if(this.opts.prev_text && (current_page > 0 || this.opts.prev_show_always)){
fragment.append(this.createLink(current_page-1, current_page, {text:this.opts.prev_text, classes:"prev"}));
}
// Generate starting points
if (interval.start > 0 && this.opts.num_edge_entries > 0)
{
end = Math.min(this.opts.num_edge_entries, interval.start);
this.appendRange(fragment, current_page, 0, end);
if(this.opts.num_edge_entries < interval.start && this.opts.ellipse_text)
{
jQuery("<span>"+this.opts.ellipse_text+"</span>").appendTo(fragment);
}
}
// Generate interval links
this.appendRange(fragment, current_page, interval.start, interval.end);
// Generate ending points
if (interval.end < np && this.opts.num_edge_entries > 0)
{
if(np-this.opts.num_edge_entries > interval.end && this.opts.ellipse_text)
{
jQuery("<span>"+this.opts.ellipse_text+"</span>").appendTo(fragment);
}
begin = Math.max(np-this.opts.num_edge_entries, interval.end);
this.appendRange(fragment, current_page, begin, np);

}
// Generate "Next"-Link
if(this.opts.next_text && (current_page < np-1 || this.opts.next_show_always)){
fragment.append(this.createLink(current_page+1, current_page, {text:this.opts.next_text, classes:"next"}));
}
$('a', fragment).click(eventHandler);
return fragment;
}
});

// Extend jQuery
$.fn.pagination = function(maxentries, opts){

// Initialize options with default values
opts = jQuery.extend({
items_per_page:10,
num_display_entries:10,
current_page:0,
num_edge_entries:0,
link_to:"javascript:;",
prev_text:"上页",
next_text:"下页",
ellipse_text:"...",
prev_show_always:true,
next_show_always:true,
renderer:"defaultRenderer",
callback:readRemotePage,
showRemotePageCallback:showRemotePageCallback,
id:"default_pagination",
url:"#",
loading:"加载中...",
params:{},
showResultContainer:null,
showResultCallback:function(data){return false;}
},opts||{});

var containers = this,
renderer, links, current_page;

var tipId = "callbackTip_" + opts.id;
var tipDiv = '<div id="'+ tipId +'" style="color:red;font-size:12px;position:absolute;background-color:#F8EF00;" mce_style="color:red;font-size:12px;position:absolute;background-color:#F8EF00;">'+
opts.loading +'</div>';
$("body").append(tipDiv);
$(this).ajaxStart(function(){
if(opts.showResultContainer != null){
var tip = $("#" + tipId);
var offset = $("#" + opts.showResultContainer).offset();
tip.offset(offset);
tip.show();
}
});
$(this).ajaxStop(function(){
if(opts.showResultContainer != null){
var tip = $("#" + tipId);
tip.hide();
}
});
/**
* default action to get remote page content
*/
function readRemotePage(current_page,containers){
var params = jQuery.extend(opts.params,{});
params.pageNum = current_page + 1;
$.get(opts.url,params,opts.showRemotePageCallback);
return false;
}

/**
*  callback function  to show remote page content
*/
function showRemotePageCallback(data){
if(opts.showResultContainer != null){
$("#" + opts.showResultContainer).html(data);
}else{
opts.showResultCallback(data);
}
}

/**
* This is the event handling function for the pagination links.
* @param {int} page_id The new page number
*/
function pageSelected(evt){
var links, current_page = $(evt.target).data('page_id');
containers.data('current_page', current_page);
links = renderer.getLinks(current_page, pageSelected);
containers.empty();
links.appendTo(containers);
var continuePropagation = opts.callback(current_page, containers);
if (!continuePropagation) {
if (evt.stopPropagation) {
evt.stopPropagation();
}
else {
evt.cancelBubble = true;
}
}
return continuePropagation;
}

current_page = opts.current_page;
containers.data('current_page', current_page);
// Create a sane value for maxentries and items_per_page
maxentries = (!maxentries || maxentries < 0)?1:maxentries;
opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page;

if(!$.PaginationRenderers[opts.renderer])
{
throw new ReferenceError("Pagination renderer '" + opts.renderer + "' was not found in jQuery.PaginationRenderers object.");
}
renderer = new $.PaginationRenderers[opts.renderer](maxentries, opts);

containers.each(function() {
// Attach control functions to the DOM element
this.selectPage = function(page_id){ pageSelected(page_id);}
this.prevPage = function(){
var current_page = containers.data('current_page');
if (current_page > 0) {
pageSelected(current_page - 1);
return true;
}
else {
return false;
}
}
this.nextPage = function(){
var current_page = containers.data('current_page');
if(current_page < numPages()-1) {
pageSelected(current_page+1);
return true;
}
else {
return false;
}
}
});
// When all initialisation is done, draw the links
links = renderer.getLinks(current_page, pageSelected);
containers.empty();
links.appendTo(containers);
// call callback function
opts.callback(current_page, containers);

}
})(jQuery);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息