Dynamic pagination in Jquery

前端 未结 7 2168
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-06 10:59

I have this code :



        
相关标签:
7条回答
  • 2021-02-06 11:30

    You need to count the pages using Math.ceil($(".line-content").size() / pageSize), and then dynamically add <li> for each page.

    I have moved the initialization code inside $() (i.e. the Ready Event).

    //Pagination
    pageSize = 8;
    
    $(function() {
      var pageCount = Math.ceil($(".line-content").size() / pageSize);
    
      for (var i = 0; i < pageCount; i++) {
        if (i == 0)
          $("#pagin").append('<li><a class="current" href="#">' + (i + 1) + '</a></li>');
        else
          $("#pagin").append('<li><a href="#">' + (i + 1) + '</a></li>');
      }
    
    
      showPage(1);
    
      $("#pagin li a").click(function() {
        $("#pagin li a").removeClass("current");
        $(this).addClass("current");
        showPage(parseInt($(this).text()))
      });
    
    })
    
    showPage = function(page) {
      $(".line-content").hide();
    
      $(".line-content").each(function(n) {
        if (n >= pageSize * (page - 1) && n < pageSize * page)
          $(this).show();
      });
    }
    .current {
      color: green;
    }
    #pagin li {
      display: inline-block;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <div class="line-content">1 I have some content</div>
    <div class="line-content">2 I have some content</div>
    <div class="line-content">3 I have some content</div>
    <div class="line-content">4 I have some content</div>
    <div class="line-content">5 I have some content</div>
    <div class="line-content">6 I have some content</div>
    <div class="line-content">7 I have some content</div>
    <div class="line-content">8 I have some content</div>
    <div class="line-content">9 I have some content</div>
    <div class="line-content">10 I have some content</div>
    <div class="line-content">11 I have some content</div>
    <div class="line-content">12 I have some content</div>
    
    <ul id="pagin">
    
    </ul>

    0 讨论(0)
提交回复
热议问题