Table of Contents
'+ data[i].title +'
Home Web Front-end JS Tutorial js implements loading more function instances

js implements loading more function instances

Dec 08, 2016 pm 03:23 PM
js

When a front-end page of the project displays purchased products, it is required to be able to pull down to load more. Regarding how to implement the "load more" function, there are plug-ins available online, such as the well-known pull-up to load more and pull-down to refresh functions implemented using iscroll.js.

But it is very troublesome to use in practice. Since it is a third-party plug-in, it has to be used according to the method defined by the other party, which always feels very uncomfortable to use. In addition, iscroll.js itself does not integrate more functions and needs to be expanded by itself. If you want to continue using iscroll.js to load more functions, you can check out the link given above.

The h5 project needs to implement a simple paging function. Since it is a mobile terminal, it would be better to consider using "Load More" instead of turning pages on the PC side.

Load more based on buttons

The simplest way is to give a load more button. If there is still data, click it to load more, and continue to pull a few pieces of data; until there is no more data, hide the load more button.

The effect is as follows:

js implements loading more function instances

Page html:

1

2

3

4

5

6

7

8

9

10

11

12

13

<div class="content">

  <div class="weui_panel weui_panel_access">

    <div class="weui_panel_hd">文章列表</div>

    <div class="weui_panel_bd js-blog-list">

        

    </div>

  </div>

    

  <!--加载更多按钮-->

  <div class="js-load-more">加载更多</div>

    

</div>

<script src="js/zepto.min.js"></script>

Copy after login

Load more button style: loadmore.css:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

@charset "utf-8";

  

.js-load-more{

  padding:0 15px;

  width:120px;

  height:30px;

  background-color:#D31733;

  color:#fff;

  line-height:30px;

  text-align:center;

  border-radius:5px;

  margin:20px auto;

  border:0 none;

  font-size:16px;

  display:none;/*默认不显示,ajax调用成功后才决定显示与否*/

}

Copy after login

Load more js code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

$(function(){

  

  /*初始化*/

  var counter = 0; /*计数器*/

  var pageStart = 0; /*offset*/

  var pageSize = 4; /*size*/

    

  /*首次加载*/

  getData(pageStart, pageSize);

    

  /*监听加载更多*/

  $(document).on(&#39;click&#39;, &#39;.js-load-more&#39;, function(){

    counter ++;

    pageStart = counter * pageSize;

      

    getData(pageStart, pageSize);

  });

});

Copy after login

There is not much code here. Among them, getData(pageStart, pageSize) is the business logic code, which is responsible for pulling data from the server. Here’s an example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

function getData(offset,size){

  $.ajax({

    type: &#39;GET&#39;,

    url: &#39;json/blog.json&#39;,

    dataType: &#39;json&#39;,

    success: function(reponse){

    

      var data = reponse.list;

      var sum = reponse.list.length;

    

      var result = &#39;&#39;;

        

      /****业务逻辑块:实现拼接html内容并append到页面*********/

        

      //console.log(offset , size, sum);

        

      /*如果剩下的记录数不够分页,就让分页数取剩下的记录数

      * 例如分页数是5,只剩2条,则只取2条

      *

      * 实际MySQL查询时不写这个不会有问题

      */

      if(sum - offset < size ){

        size = sum - offset;

      }

        

      /*使用for循环模拟SQL里的limit(offset,size)*/

      for(var i=offset; i< (offset+size); i++){

        result +=&#39;<div class="weui_media_box weui_media_text">&#39;+

            &#39;<a href="&#39;+ data[i].url +&#39;" target="_blank"><h4 id="nbsp-data-i-title-nbsp">&#39;+ data[i].title +&#39;</h4></a>&#39;+

            &#39;<p class="weui_media_desc">&#39;+ data[i].desc +&#39;</p>&#39;+

          &#39;</div>&#39;;

      }

    

      $(&#39;.js-blog-list&#39;).append(result);

        

      /*******************************************/

    

      /*隐藏more按钮*/

      if ( (offset + size) >= sum){

        $(".js-load-more").hide();

      }else{

        $(".js-load-more").show();

      }

    },

    error: function(xhr, type){

      alert(&#39;Ajax error!&#39;);

    }

  });

}

Copy after login

It’s relatively simple.

Loading more based on scroll events
Above we implemented loading more by clicking the button, and the overall process is relatively simple. Here, I provide another way to load more: based on scroll events.

Posted the code directly:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

$(function(){

  

  /*初始化*/

  var counter = 0; /*计数器*/

  var pageStart = 0; /*offset*/

  var pageSize = 7; /*size*/

  var isEnd = false;/*结束标志*/

    

  /*首次加载*/

  getData(pageStart, pageSize);

    

  /*监听加载更多*/

  $(window).scroll(function(){

    if(isEnd == true){

      return;

    }

  

    // 当滚动到最底部以上100像素时, 加载新内容

    // 核心代码

    if ($(document).height() - $(this).scrollTop() - $(this).height()<100){

      counter ++;

      pageStart = counter * pageSize;

        

      getData(pageStart, pageSize);

    }

  });

});

Copy after login

It can be seen that the code has not changed much. It mainly depends on the judgment conditions in the core code: when scrolling to 100 pixels above the bottom, new content is loaded.

Business logic getData(pageStart, pageSize) only needs to change the logic in if ( (offset + size) >= sum) to:

1

2

3

if ( (offset + size) >= sum){

  isEnd = true;//没有更多了

}

Copy after login

.

Of course, there are still areas that need to be optimized, such as: How to prevent the server from scrolling too fast and causing multiple requests before the server has time to respond?

Comprehensive example

Through the above example, it is obvious that the second one is better, no need to click. But there is a problem with the second method:

If you set the page size to display 2 or 3 items each time (size=2), and the total records are 20, you will find that you cannot trigger the logic of scrolling down to load more. At this time it would be nice to have a click button to load more.

Therefore, we can combine the above two methods:

By default, scroll events are used to load more. When the display number is too small to trigger the logic of scrolling down to load more, use Load More Clicks event.
Here, I simply abstracted the behavior of loading more and wrote a simple plug-in:

loadmore.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

/*

 * loadmore.js

 * 加载更多

 *

 * @time 2016-4-18 17:40:25

 * @author 飞鸿影~

 * @email jiancaigege@163.com

 * 可以传的参数默认有:size,scroll 可以自定义

 * */

  

;(function(w,$){

    

  var loadmore = {

    /*单页加载更多 通用方法

     *

     * @param callback 回调方法

     * @param config 自定义参数

     * */

    get : function(callback, config){

      var config = config ? config : {}; /*防止未传参数报错*/

  

      var counter = 0; /*计数器*/

      var pageStart = 0;

      var pageSize = config.size ? config.size : 10;

  

      /*默认通过点击加载更多*/

      $(document).on(&#39;click&#39;, &#39;.js-load-more&#39;, function(){

        counter ++;

        pageStart = counter * pageSize;

          

        callback && callback(config, pageStart, pageSize);

      });

        

      /*通过自动监听滚动事件加载更多,可选支持*/

      config.isEnd = false; /*结束标志*/

      config.isAjax = false; /*防止滚动过快,服务端没来得及响应造成多次请求*/

      $(window).scroll(function(){

          

        /*是否开启滚动加载*/

        if(!config.scroll){

          return;

        }

          

        /*滚动加载时如果已经没有更多的数据了、正在发生请求时,不能继续进行*/

        if(config.isEnd == true || config.isAjax == true){

          return;

        }

          

        /*当滚动到最底部以上100像素时, 加载新内容*/

        if ($(document).height() - $(this).scrollTop() - $(this).height()<100){

          counter ++;

          pageStart = counter * pageSize;

            

          callback && callback(config, pageStart, pageSize);

        }

      });

  

      /*第一次自动加载*/

      callback && callback(config, pageStart, pageSize);

    },

        

  }

  

  $.loadmore = loadmore;

})(window, window.jQuery || window.Zepto);

Copy after login

How to use it? It's simple:

1

2

3

4

5

$.loadmore.get(getData, {

  scroll: true, //默认是false,是否支持滚动加载

  size:7, //默认是10

  flag: 1, //自定义参数,可选,示例里没有用到

});

Copy after login

The first parameter is the callback function, which is our business logic. I posted the final modified business logic method:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

function getData(config, offset,size){

  

  config.isAjax = true;

  

  $.ajax({

    type: &#39;GET&#39;,

    url: &#39;json/blog.json&#39;,

    dataType: &#39;json&#39;,

    success: function(reponse){

      

      config.isAjax = false;

  

      var data = reponse.list;

      var sum = reponse.list.length;

        

      var result = &#39;&#39;;

        

      /************业务逻辑块:实现拼接html内容并append到页面*****************/

        

      //console.log(offset , size, sum);

        

      /*如果剩下的记录数不够分页,就让分页数取剩下的记录数

      * 例如分页数是5,只剩2条,则只取2条

      *

      * 实际MySQL查询时不写这个

      */

      if(sum - offset < size ){

        size = sum - offset;

      }

  

        

      /*使用for循环模拟SQL里的limit(offset,size)*/

      for(var i=offset; i< (offset+size); i++){

        result +=&#39;<div class="weui_media_box weui_media_text">&#39;+

            &#39;<a href="&#39;+ data[i].url +&#39;" target="_blank"><h4 id="nbsp-data-i-title-nbsp">&#39;+ data[i].title +&#39;</h4></a>&#39;+

            &#39;<p class="weui_media_desc">&#39;+ data[i].desc +&#39;</p>&#39;+

          &#39;</div>&#39;;

      }

  

      $(&#39;.js-blog-list&#39;).append(result);

        

      /*******************************************/

        

      /*隐藏more*/

      if ( (offset + size) >= sum){

        $(".js-load-more").hide();

        config.isEnd = true; /*停止滚动加载请求*/

        //提示没有了

      }else{

        $(".js-load-more").show();

      }

    },

    error: function(xhr, type){

      alert(&#39;Ajax error!&#39;);

    }

  });

}

Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles