结合豆瓣搜索结果进行分页(完整)

  使用豆瓣api,得到分页结果。相当于从后台数据库获得的结果一样。所不同的是,没法事先知道页数。虽然通过请求api可以获得总页数,但由于ajax是异步的,所以对于分页一开始就要给出总页数来说,这是没有意义的。我使用了一个固定总页数65(正是搜索javascript书籍返回的总页数)。所以其他书籍是并不是65页,会出现多页或者少页的情况,这并不是bug。

特点

  1,全程不需要接触后台,前端独立就可以(我找过好长时间都没找过完整的例子)。
  2,使用了bootstrap的pagination制作页码和panel制作放置结果的面板。
  

代码如下

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <link rel="stylesheet" href="css/bootstrap.css" /><!-- 换成自己的目录 -->
        <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
    </head>
    <style>
      .pagination> li > a {
        cursor: pointer;
      }
      .pagination > li > span {
        margin-left: 0;
        color: #ccc;
        background-color: transparent;
        cursor: default;
      }
      .pagination > li > span:hover {
      color: #ccc;    
      background-color: transparent;
      cursor: default; 
      }
      .m20 {
        margin: 20px 0;
      }

    </style>
    <body>

      <div class="container-fluid">

        <div class="col-md-12">
          <div class="panel panel-default">
            <div class="panel-heading">
              <form class="input-group">
                <input type="text" value="javascript" class="form-control" id="bookName" placeholder="请输入书名" required="required"/>
                <span class="input-group-btn">
                  <button class="btn" id="search">搜索</button>
                </span>
              </form>
            </div>
            <div class="panel-body">
              <table class="table table-bordered">
                <thead>
                  <th>书名</th>
                  <th>作者</th>
                  <th>出版日期</th>
                  <th>平均分</th>
                  <th>价格</th>
                </thead>
                <tbody id="tbody">

                </tbody>
              </table>
            </div>
          </div>

        <div class="row">
          <div class="col-md-6">
            <div id="test"></div>
          </div>

          <div class="col-md-4">
            <div class="input-group m20"><!-- 保持与#test中的.pagination对齐 -->
              <input type="text" class="form-control" id="page"/>
              <span class="input-group-btn">
                <button class="btn btn-default" id="jumpToPage">GO</button>
              </span>
            </div>
          </div>
        </div>

        <div id="result" class="alert alert-info"></div>
        </div>
      </div>


  <script type="text/javascript" src="js/jquery-1.11.2.min.js" ></script> <!-- 换成自己的目录 -->
  <script type="text/javascript" src="js/bootstrap.js" ></script> <!-- 换成自己的目录 -->
  <script type="text/javascript">
    var partPageModule = ( function ( $ ) {
      var 
        initPager = null,// 初始换分页函数
        setPagerHTML = null,// 生成分的页HTML代码
        pageClick = null,// 每一页按钮的点击事件
        ajax = null, // ajax请求后台数据
        renderButton = null,
        $content = $( '' ) // 动态生成的页码
      ;


      /* 功能:完成初始化
       * @totalPages 总页数,从后端获取
       * @currentPage 当前所在的页数
       */
      initPager = function ( totalPages, currentPage ) {
        $content = setPagerHTML({
          currentPage: currentPage,
          totalPages: totalPages,
          pageClick: PageClick
        })
        $( '#test' ).empty().append( $content );// 得到分页后添加到#test
        $( '#jumpToPage' ).click( function ( e ) {// 绑定GO按钮的点击事件
          e.preventDefault();
          PageClick( totalPages, $('#page').val() * 1);
        })
        $( '#page' ).keyup( function ( e ) {// Enter键绑定搜索事件
          if ( e.keyCode === 13 ) {
            $( '#jumpToPage').trigger( 'click' );
          }
        })
        $( '#result' ).html( '你点击的是第' + currentPage + '页')
      };

      /* 功能:页码点击事件。重新生成所有页码,并且使用ajax获取数据
       */
      PageClick = function ( totalPages, currentPage ) {
        initPager( totalPages, currentPage );
        ajax( currentPage );// 使用jsonp请求豆瓣
      }

      ajax = function ( currentPage ) {
        var 
          $input = $( '#bookName' ),
          bookName = '',
          $tbody = $( '#tbody' )
//        totalPages
        ;

        bookName = $input.val();

        if ( !bookName ) { // 如果没有输入,就不要发送请求了
          $input.focus();
          return;
        } else {
          $.ajax({
            type: 'get',
            url: 'https://api.douban.com/v2/book/search',// 豆瓣图书api
            dataType: 'jsonp',
            data: {
              q: bookName,
              start: ( parseInt( currentPage )-1 )*20 || 0
            },
            success: function ( data ) {
              var 
                html = '',
                books = data.books
              ;

//            totalPages = Math.ceil( data.total / data.count );

              books.forEach( function ( value, index ) {
                html  += '<tr>'
                      + '<td><a href="' + value.alt + '">' + value.title + '</a></td>'
                      + '<td>' + value.author + '</td>'
                      + '<td>' + value.pubdate + '</td>'
                      + '<td>' + value.rating.average + '</td>'
                      + '<td>' + value.price + '</td>'
                      + '</tr>';  
              })

              $tbody.html( html );
            }
          })
        }

//      return totalPages;
      }

      setPagerHTML = function ( options ) {
        var 
          currentPage = options.currentPage,
          totalPages = options.totalPages,
          pageClick = options.pageClick,
          $content = $('<ul class="pagination"></ul>'),
          startPage = 1,
          nextPage = currentPage + 1,//不需要考虑超出问题,后面有条件
          prevPage = currentPage - 1
        ;

        /* 逻辑处理,根据点击的不同的页生成不同的ul */
        if ( currentPage == startPage ) {//当前页是起始页
          $content.append( '<li><span>首页</span></li>' ); // 首页不可用
          $content.append( '<li><span>上一页</span></li>' ); // 上一页不可用
        } else { // 不是起始页
          $content.append( renderButton( totalPages, 1, pageClick, '首页') ); // 生成首页并绑定事件
          $content.append( renderButton( totalPages, prevPage, pageClick, '上一页') ); // 生成上一页并绑定事件
        }

        if ( totalPages <=5 && currentPage <= 5 ) {// 总页数小于5,当前页小于5,全部生成页码
          for ( var i = 1; i <= totalPages; i++ ) {
            if( i === currentPage ) {
              $content.append( '<li class="active><span>' + i + '</span></li>' );// 当前页不可点击
            } else {
              $content.append( renderButton( totalPages, i, pageClick, i) );// 其他页可以点击
            }
          }
        } else if ( totalPages > 5 && totalPages - currentPage <= 2 ) {// 总页数大于5,当前页接近总页数,前面显示...,后面显示到结尾的页码
          $content.append( '<li><span>...</span></li>' );
          for( var i = totalPages - 4; i <= totalPages; i++ ) {
            if ( i === currentPage ) {
              $content.append( '<li class="active"><span>' + i + '</span></li>' );
            } else {
              $content.append( renderButton( totalPages, i, pageClick, i) );
            }
          }
        } else if ( totalPages > 5 && currentPage > 3) {// 总页数大于5,当前页在中间,前后生成...,生成中间页码
          $content.append( '<li><span>...</span></li>' );
          for ( var i = currentPage - 2; i < currentPage + 2; i++ ) {
            if ( i === currentPage ) {
              $content.append( '<li class="active"><span>' + i + '</span></li>' );
            } else {
              $content.append( renderButton( totalPages, i ,pageClick, i) );
            }
          }
          $content.append( '<li><span>...</span></li>' );
        } else if ( totalPages > 5 && currentPage <= 3 ) {// 总页数大于5,当前页接近第一页,显示前面页码,后面显示...
          for ( var i = 1; i <= 5; i++ ) {
            if ( i === currentPage ) {
              $content.append( '<li class="active"><span>' + i + '</span></li>' );
            } else {
              $content.append( renderButton( totalPages, i ,pageClick, i) );
            }
          }
          $content.append( '<li><span>...</span></li>' );
        }

        if ( currentPage == totalPages ) {//当前页是末页
          $content.append( '<li><span>下一页</span></li>' ); // 下一页不可用
          $content.append( '<li><span>末页</span></li>' ); // 末页不可用
        } else { // 不是起始页
          $content.append( renderButton( totalPages, nextPage, pageClick, '下一页') ); // 生成首页并绑定事件
          $content.append( renderButton( totalPages, totalPages, pageClick, '末页') ); // 生成上一页并绑定事件
        }

        return $content;
      }

      renderButton = function ( totalPages, goPageIndex, eventHander, text ) {
        var $gotoPage = $( '<li><a title="第' + goPageIndex + '页">' + text + '</a></li>' );
        $gotoPage.click( function () {
          eventHander( totalPages, goPageIndex );
        })

        return $gotoPage;
      }


      return {
        init: initPager,
        ajax: ajax
      } 
    }(jQuery))

    $( function () {


      $( '#search' ).click( function ( e ) {
        e.preventDefault();
        var totalPage = partPageModule.ajax(1);// 由于ajax是异步的,
        totalPage = totalPage || 65;// 所以这个总页数是不准确的。一般这个数据是后端返回的。这里的65是javascript搜索的页数,不同的书籍搜索结果不一样,由于ajax异步执行,所以这里会默认为65。这里不是bug。
        partPageModule.init( totalPage, 1 );
      })

      $( '#bookName' ).keyup( function ( e ) {
        if ( e.keyCode === 13 ) {
          $( '#search' ).trigger( 'click' );
        }
      })

      $( '#search' ).trigger( 'click' );
    })
  </script>
    </body>
</html>
<!-- https://api.douban.com/v2/book/search -->
<!--
  参数        意义                备注
  q       查询关键字           q和tag必传其一
  tag     查询的tag           q和tag必传其一
  start   取结果的offset      默认为0
  count   取结果的条数         默认为20,最大为100
-->     

参考

http://bbs.csdn.net/topics/390734775?page=1 书中的逻辑处理部分使用的是这里的代码,不过做了修改。

效果展示

https://yuwanlin.github.io/general/%E5%88%86%E9%A1%B5/%E7%BB%93%E5%90%88%E8%B1%86%E7%93%A3%E6%90%9C%E7%B4%A2%E7%BB%93%E6%9E%9C%E8%BF%9B%E8%A1%8C%E5%88%86%E9%A1%B5.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值