简体   繁体   中英

Table pagination with jQuery

I'm trying to simulate a pagination using jQuery and have worked out all the essential pagination elements but can't get the navigation part to work. It worked with a list element but not with this table structure. Can someone please tell me what could be the issue?

var show_per_page = 2;
var number_of_items = $('tbody').children().size();
var number_of_pages = Math.ceil(number_of_items / show_per_page);
var current_link = 0;

$('table').after('<div class=controls></div>');
var navigation_html = '<a class="prev" onclick="previous()">...</a>';

while (number_of_pages > current_link) {
  navigation_html += '<a class="page" onclick="go_to_page(' + current_link + ')" longdesc="' + current_link + '">' + (current_link + 1) + '</a>';
  current_link++;
}
navigation_html += '<a class="next" onclick="next()">...</a>';

$('.controls').html(navigation_html);
$('.controls .page:first').addClass('active');

$('tbody').children().hide();
$('tbody').children().slice(0, show_per_page).show();

function go_to_page(page_num) {
  start_from = page_num * show_per_page;
  end_on = start_from + show_per_page;

  $('tbody').children().hide().slice(start_from, end_on).show();

  $('.page[longdesc=' + page_num + ']').addClass('active').siblings('.active').removeClass('active');

}

function previous() {
  new_page = current_link - 1;

  if ($('.active').prev('.page').length == true) {
    go_to_page(new_page);
  }
}

function next() {
  new_page = current_link + 1;

  if ($('.active').next('.page').length == true) {
    go_to_page(new_page);
  }
  $("a.prev").show();

}

Demo JS Fiddle

Well, the immediate issue I can see has to do with function scope. Rather than solving it, I'll tell you that the go_to_page function that you're adding to the links is out of scope.

EDIT: Looks like that's a jsfiddle issue.

Your code works, it has to do to JSfiddle wrapping the function names

I ran your code on a local file, just need to include jquery.

This is the whole code that I used: https://gist.github.com/kEpEx/4422d441dbd0b71dfd3d

在此处输入图片说明

No Wrap - in <body> JS Fiddle Javascript设置更改为No Wrap - in <body>并包装了显式的load函数,现在可以使用了。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM