开发者

Counting divs for pagination in Jquery

I want to create a nice pagination in Jquery for a number of divs I have. EG:

<div class="container">  
    <div id="one">content</div>  
    <div id="two">content</div>  
    <div id="three">content</div>  
    <div id="four">content</div>  
</div> 

The number will not always be the same so I need to count the divs, and display a pagination like the one below.

1|2|3|4

Clicking on the page number would display the relevant div. I know how to show and hide elements using J开发者_Go百科query and css and have figured out I can count the divs using

var numPages = $('.container').size();

but I can't work out how I can display the pagination.

Any pointers?


Something like this:

// Get all immediate child divs and their count
var $divs = $('div.container > div');
var pages = $divs.length;

// Hide every one but the first
$divs.not(':first').hide();

// Create a container for the pagination
$ul = $('<ul />');

// Create links for pagination inside the ul
for(var i = 0; i < pages; i++) {
    $ul.append($('<li><a href="#" class="pagination" rel="'+i+'">'+i+'</a></li>'));
}

// Insert the pagination container
$('div.container').before($ul);

// Behaviour for clicking the links inside pagination container
$ul.find('a.pagination').click(function() {
    // Get the index from current element's rel attribute
    var index = parseInt($(this).attr('rel'), 10);
    // Hide every div and show the div at the current index's location
    $divs.hide().eq(index).show();
    return false;
});

Haven't tested that but it should give you starters. Basically it just creates an ul element which controls which divs show up.


Use the .addClass() and .removeClass - just put a class on the first page (div) that shows, and all the others that hides, and swap them (hiding one with current visibility by adding the hide class and removing the show class, and the inverse for the new page you wish to show by adding/removing CSS classes.


How about this?

    // Opens a certain div in the .container
    function openUpPage(id) {
        $('.container div').hide(); // hide all divs in container
        $('#'+id).show(); // show only this one
    }

    // Gets called on document load
    $(function() {
        var i = 0;
        $('.container div').each(function (){
            i++;
            $(this).hide(); // hide
            $('#paginator').append("<a href=\"javascript: openUpPage('"+$(this).attr('id')+"')\">"+i+"</a>|");
        });

    });

Note add this to your HTML where the pagination should go:

<div id="paginator">  </div>

Otherwise, there's lots of plugins that do this for you (such as tablesorter with tablesorter.paginated) or you can use jQuery UI tabs. Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜