在 Jquery 中计算分页的 div

编程入门 行业动态 更新时间:2024-10-26 13:25:35
本文介绍了在 Jquery 中计算分页的 div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Jquery 中为我拥有的多个 div 创建一个漂亮的分页.EG:

<div id="one">内容</div><div id="两个">内容</div><div id="三">内容</div><div id="四">内容</div>

数字并不总是相同的,所以我需要计算 div,并显示如下所示的分页.

1|2|3|4

点击页码会显示相关的div.我知道如何使用 Jquery 和 css 显示和隐藏元素,并且我发现我可以使用

来计算 div

var 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:关键词]

本文发布于:2023-03-26 23:30:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/670267.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分页   Jquery   div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!