我的分页工作正常,但我想在我的分页代码中添加“上一页”和“下一页”按钮。
我想要的是:
这是我的HTML标记:
<table class="paginated">
<thead>
<tr>
<th scope="col">A</th>
<th scope="col">B</th>
<th scope="col">C</th>
<th scope="col">D</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
...... many many more rows in <tr>...</tr> .......
</tbody>
</table>
这是我的jQuery代码:
$('td', 'table').each(function(i) {
$(this).text(i+1);
});
$('table.paginated').each(function() {
var currentPage = 0;
var numPerPage = 5;
var $table = $(this);
$table.bind('repaginate', function() {
$table.find('tbody tr').hide().slice(currentPage * numPerPage, (currentPage + 1) * numPerPage).show();
});
$table.trigger('repaginate');
var numRows = $table.find('tbody tr').length;
var numPages = Math.ceil(numRows / numPerPage);
var $pager = $('<div class="pager"></div>');
var $previous = $('<span class="previous"><<</spnan>');
var $next = $('<span class="next">>></spnan>');
for (var page = 0; page < numPages; page++) {
$('<span class="page-number"></span>').text(page + 1).bind('click', {
newPage: page
}, function(event) {
currentPage = event.data['newPage'];
$table.trigger('repaginate');
$(this).addClass('active').siblings().removeClass('active');
}).appendTo($pager).addClass('clickable');
}
$pager.insertBefore($table).find('span.page-number:first').addClass('active');
$previous.insertBefore('span.page-number:first');
$next.insertAfter('span.page-number:last');
});
这里是我的JsFiddle演示:http://jsfiddle.net/Xugej/1442/
希望有人可以帮助我。
答案 0 :(得分:2)
我能想到的最简单的解决方案是让前一个和下一个按钮在正确的标签按钮上触发“点击”事件:
$next.click(function (e) {
$previous.addClass('clickable');
$pager.find('.active').next('.page-number.clickable').click();
});
$previous.click(function (e) {
$next.addClass('clickable');
$pager.find('.active').prev('.page-number.clickable').click();
});
如果你想让它们适当地激活/不活动,我们需要更多的逻辑。每当表格重新组合时,您需要检查下一个和上一个按钮是否应该可点击:
$table.on('repaginate', function () {
$next.addClass('clickable');
$previous.addClass('clickable');
setTimeout(function () {
var $active = $pager.find('.page-number.active');
if ($active.next('.page-number.clickable').length === 0) {
$next.removeClass('clickable');
} else if ($active.prev('.page-number.clickable').length === 0) {
$previous.removeClass('clickable');
}
});
});
$table.trigger('repaginate');