簡體   English   中英

收集正確的onScroll數據以觸發AJAX功能

[英]Gathering proper onScroll data to trigger AJAX function

我在滾動時調用一個AJAX函數:

// Collecting scroll info
$('.overthrow').each(function() {

  var self = this;
  var path2root = ".";
  var subcategoryId = $(this).attr('data-subcategoryId');
  var page = 1;

  $(this).bind('scroll', function() { 

    var scrollAmount = $(self).scrollLeft();
    var documentWidth = $(self).data('currentElementPosition') || $(document).width();
    var scrollPercent = (scrollAmount / documentWidth) * 100;

    if (scrollPercent > 80) { 

      page++;

      console.log("process.php?subcategoryId=" + subcategoryId + "&page=" + page);

      // AJAX function for processing JSON
      $.ajax({
        url: "process.php?subcategoryId=" + subcategoryId + "&page=" + page,
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
          for(i = 0 ; i < data.length; i++) {
            var articleId = data[i].articleResult.articleId;
            var title = data[i].articleResult.title;
            var subhead = data[i].articleResult.subhead;
            var image = data[i].articleResult.image;
            var response = "<td><div class='articleResult'><a href='" + path2root + "/article/article.php?articleId=" + articleId + "'><img src='" + image + "' width='120'/></a><br><h3><a href='" + path2root + "/article/article.php?articleId=" + articleId + "'>" + title.substring(0,25) + "</a></h3></div></td>";

            var appendedData = $(self).find("table tbody tr td:last-child").after(response).fadeIn('slow');
            $(self).data('currentElementPosition', appendedData.position().left);
          };
        }
      });
    };
  });
});

我的問題是,一旦第一個響應附加到內容,我開始滾動80%到新的結果,我滾動的每個像素再次調用相同的AJAX函數,而不是等待用戶滾動80%的寬度新窗口大小。 有效地為每個像素進行AJAX調用,滾動超過80%。

if語句是錯誤的路徑嗎? 我應該提供某種類型的回調來動態驅動觸發AJAX功能的整數嗎?

我會使用jQuery的one()來綁定它一次,然后在成功回調中為你的ajax重新綁定它(或之后的任何地方)

另一種方法是保存對AJAX調用后附加到DOM的任何內容的引用,獲取其位置,並將滾動位置與之比較。 換句話說,假設在上面的示例中,$(this)是插入通過AJAX返回的所有數據的父容器,您可以執行以下操作:

$(this).scroll(function () {
               var scrollAmount = $(this).scrollLeft();
               var documentWidth = $(this).data('currentElementPosition') || $(document).width()
               var scrollPercent = (scrollAmount / documentWidth ) * 100;
                  if (scrollPercent > 80) { 
                      // AJAX function success
                          var appendedData = $(data_returned_from_ajax_call).appendTo($(this))
                          $(this).data('currentElementPosition', appendedData.position().left)
                     };
                  });
}

僅僅是一個FYI,需要注意的一點是,jQuery的.offset()方法將為您提供相對於文檔的元素位置,而.position()將為您提供相對於其父容器的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM