I can't get this script to work well. Can someone help me? First, I would like to make it that I can use it for multiple
- elements.
One other thing, I would like to make it so that if I have more than 5
elements it appends a "next" button and then on page 2, it appends "prev" and "next" buttons. Also, if on the last page "next" button shouldn't be seen.Here is my current code:
$('div').each(function(){
$(this).append('prev | next');
$(this).find('ul li:gt(4)').hide();
$(this).find('.next').click(function() {
var last = $('ul').children('li:visible:last');
last.nextAll(':lt(5)').show();
last.next().prevAll().hide();
});
$(this).find('.prev').click(function() {
var first = $('ul').children('li:visible:first');
first.prevAll(':lt(5)').show();
first.prev().nextAll().hide()
});
});
解决方案
You can do something like this (Fiddle):
function check_navigation_display(el) {
//accepts a jQuery object of the containing div as a parameter
if ($(el).find('ul').children('li').first().is(':visible')) {
$(el).children('.prev').hide();
} else {
$(el).children('.prev').show();
}
if ($(el).find('ul').children('li').last().is(':visible')) {
$(el).children('.next').hide();
} else {
$(el).children('.next').show();
}
}
$('div').each(function () {
$(this).append('prev | next');
$(this).find('ul li:gt(4)').hide();
check_navigation_display($(this));
$(this).find('.next').click(function () {
var last = $(this).siblings('ul').children('li:visible:last');
last.nextAll(':lt(5)').show();
last.next().prevAll().hide();
check_navigation_display($(this).closest('div'));
});
$(this).find('.prev').click(function () {
var first = $(this).siblings('ul').children('li:visible:first');
first.prevAll(':lt(5)').show();
first.prev().nextAll().hide()
check_navigation_display($(this).closest('div'));
});
});