繁体   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