tags:

views:

130

answers:

3

I have cloned some pagination using jQuery's clone() method. When I am attempting to show the current page number (addClass('active')) the behaviour is only occuring on the cloned version of the element. Can anybody help?

$(document).ready(function() {
 $('table.paginated').each(function() {
  var currentPage = 0;
  var numPerPage = 10;
  var $table = $(this);
  var repaginate = function() {
  $table.find('tbody tr').hide()
   .slice(currentPage * numPerPage,
    (currentPage + 1) * numPerPage)
   .show();
     };
  var numRows = $table.find('tbody tr').length;
  var numPages = Math.ceil(numRows / numPerPage);
  var $pager = $('<div class="pager"></div>');
   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'];
   repaginate();
   $(this).addClass('active')
    .siblings().removeClass('active');
  }).appendTo($pager).addClass('clickable');
 }
 $pager.insertBefore($table).clone(true).insertAfter($table)
  .find('span.page-number:first').addClass('active');
 });
});
A: 

The clone function creates a new wrapped set consisting of the new element. The addClass function is operating on the single element instead of both the original item and its clone.

One alternative, is to call end() after you've applied the class. This function will set your context back to the original wrapped set.

$pager 
  .insertBefore($table)
  .clone(true)
    .insertAfter($table)
    .find('span.page-number:first')
    .addClass('active')
    .end()
  .addClass('active');
David Andres
A: 
'span.page-number:first'

expand selector. Right now it selects all span.page-number then selects the first one. if you do something like

"div span.pagenumber:first"

it just might work.

Update as pointed out below, clone just duplicates the element it does not from this point track all the clones etc, it just does exactly that - clone the element and forget about it.

Dmitri Farkov
A: 

clone() select the cloned element. In this instruction:

$pager.insertBefore($table).clone(true).insertAfter($table)
                .find('span.page-number:first').addClass('active');

it's clear that addClass is only applied to the clone i.e. after clone(true)...,

najmeddine