【问题标题】:Counting divs for pagination in Jquery在Jquery中计算分页的div
【发布时间】:2011-02-20 09:44:23
【问题描述】:

我想在 Jquery 中为我拥有的许多 div 创建一个漂亮的分页。例如:

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

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

1|2|3|4

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

计算 div

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

但我不知道如何显示分页。

任何指针?

【问题讨论】:

    标签: jquery count pagination html


    【解决方案1】:

    类似这样的:

    // 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;
    });
    

    尚未对此进行测试,但它应该可以让您入门。基本上它只是创建一个 ul 元素来控制显示哪些 div。

    【讨论】:

    • 干杯,我会试试这个:)
    【解决方案2】:

    使用 .addClass() 和 .removeClass - 只需在显示的第一页 (div) 上放置一个类,并在所有其他隐藏的页面上放置一个类,然后交换它们(通过添加隐藏类并删除以当前可见性隐藏一个显示类,以及您希望通过添加/删除 CSS 类来显示的新页面的反面。

    【讨论】:

      【解决方案3】:

      这个怎么样?

          // 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>|");
              });
      
          });
      

      请注意将此添加到您的 HTML 中应该分页的位置:

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

      否则,有很多插件可以为您执行此操作(例如带有 tablesorter.paginated 的 tablesorter),或者您可以使用 jQuery UI 选项卡。祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-04
        • 1970-01-01
        • 2017-06-15
        • 1970-01-01
        • 2014-09-16
        • 2016-07-02
        • 2011-11-16
        • 1970-01-01
        相关资源
        最近更新 更多