问题描述
我想在 Jquery 中为我拥有的多个 div 创建一个漂亮的分页.EG:
<div id="one">内容</div><div id="两个">内容</div><div id="三">内容</div><div id="四">内容</div>
数字并不总是相同的,所以我需要计算 div,并显示如下所示的分页.
1|2|3|4
点击页码会显示相关的div.我知道如何使用 Jquery 和 css 显示和隐藏元素,并且我发现我可以使用
来计算 divvar numPages = $('.container').size();
但我不知道如何显示分页.
有什么指点吗?
解决方案是这样的:
//获取所有直接子 div 及其计数var $divs = $('div.container > div');var pages = $divs.length;//隐藏除第一个之外的所有$divs.not(':first').hide();//为分页创建一个容器$ul = $('');//在 ul 中创建分页链接for(var i = 0; i < pages; i++) {$ul.append($('<li><a href="#" class="pagination" rel="'+i+'">'+i+'</a></li>'));}//插入分页容器$('div.container').before($ul);//点击分页容器内的链接的行为$ul.find('a.pagination').click(function() {//从当前元素的 rel 属性中获取索引var index = parseInt($(this).attr('rel'), 10);//隐藏每个 div 并在当前索引的位置显示该 div$divs.hide().eq(index).show();返回假;});
还没有测试过,但它应该给你入门.基本上它只是创建一个 ul 元素来控制显示哪些 div.
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 Jquery 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.
这篇关于在 Jquery 中计算分页的 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论