JQuery實現 上滑加載更多

使用jQuery實現HTML5頁面上滑加載更多功能的方案:

1. 頁面結構

<div id="content-container">
  <!-- 這裏原本應由v-for循環生成的div.item將由JavaScript動態添加 -->
</div>

<!-- 加載提示區域 -->
<div id="load-more" style="display:none;">
  <p>Loading...</p>
</div>

2. JavaScript(使用jQuery)

$(document).ready(function () {
  var items = []; // 存儲已加載的數據項
  var page = 1; // 當前請求頁碼
  var loadingMore = false; // 是否正在加載更多
  var hasMore = true; // 是否還有更多數據可供加載

  function fetchData() {
    loadingMore = true;
    $('#load-more').show(); // 顯示加載提示

    $.ajax({
      url: 'your-api-url',
      type: 'GET',
      data: { page: page, limit: 15 },
      success: function (response) {
        var newItems = response.items; // 假設API返回數據結構中包含一個名爲items的數組
        if (newItems.length < 15) {
          hasMore = false; // 如果本次加載數量不足15條,說明已無更多數據
        }
        $.each(newItems, function (index, item) {
          var newItemHtml = '<div class="item">' + /* 渲染單個數據項內容 */ + '</div>';
          $('#content-container').append(newItemHtml);
        });
        page++;
        loadingMore = false;
        $('#load-more').hide(); // 隱藏加載提示
      },
      error: function (jqXHR, textStatus, errorThrown) {
        console.error('Error fetching more data:', textStatus, ', Details:', errorThrown);
        loadingMore = false;
        $('#load-more').hide(); // 隱藏加載提示
      },
    });
  }

  $(window).on('scroll', function () {
    var contentContainer = $('#content-container');
    var threshold = 100;
    var containerOffset = contentContainer.offset().top + contentContainer.outerHeight();
    var windowBottom = $(window).scrollTop() + $(window).height();

    if (!loadingMore && windowBottom > containerOffset + threshold && hasMore) {
      fetchData();
    }
  });

  // 初始加載第一頁數據
  fetchData();
});

解釋說明

  • 使用div#content-container來存放數據項,添加了一個隱藏的div#load-more用於顯示加載中的提示。

  • JavaScript部分,我們使用jQuery來處理DOM操作和事件監聽:

    • 定義全局變量itemspageloadingMorehasMore

    • 成功後,將新數據逐個生成對應的HTML字符串並追加到#content-container內,同時更新頁碼和loadingMore狀態。若本次加載數據不足15條,則設置hasMorefalse。若請求失敗,打印錯誤信息並恢復loadingMore狀態。在請求開始和結束時,分別顯示和隱藏加載提示。

    • 使用$(window).on('scroll', ...)監聽窗口滾動事件。在回調函數中,計算content-container距窗口底部的距離,當距離小於等於閾值(100像素),且當前未處於加載狀態且仍有更多數據時,觸發fetchData方法加載更多數據。

    • 頁面加載完成後,立即調用fetchData函數加載第一頁數據。

使用div展示數據,通過Ajax動態加載,距離底部100像素時觸發加載,加載中顯示提示,加載失敗時不重試,每次加載15條數據。



歡迎關注公-衆-號【TaonyDaily】、留言、評論,一起學習。

公衆號

Don’t reinvent the wheel, library code is there to help.

文章來源:劉俊濤的博客


若有幫助到您,歡迎點贊、轉發、支持,您的支持是對我堅持最好的肯定(_)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章