2017年12月25日
jquery-weui滚动加载报错问题解决
监听事件 infinite(),下面是源码,infinite(distance)接收distance参数,默认的 distance 值是 50,表示滚动到距离底部 50 px 的时候会触发加载。所以页面初始化需要把请求的数据渲染html元素填满页面才会触发。
引入js
+function ($) {
"use strict";
var Infinite = function(el, distance) {
this.container = $(el);
this.container.data("infinite", this);
this.distance = distance || 50;
this.attachEvents();
}
Infinite.prototype.scroll = function() {
var container = this.container;
var offset = container.scrollHeight() - ($(window).height() + container.scrollTop());
if(offset <= this.distance) {
container.trigger("infinite");
}
}
Infinite.prototype.attachEvents = function(off) {
var el = this.container;
var scrollContainer = (el[0].tagName.toUpperCase() === "BODY" ? $(document) : el);
scrollContainer[off ? "off" : "on"]("scroll", $.proxy(this.scroll, this));
};
Infinite.prototype.detachEvents = function(off) {
this.attachEvents(true);
}
var infinite = function(el) {
attachEvents(el);
}
$.fn.infinite = function(distance) {
return this.each(function() {
new Infinite(this, distance);
});
}
$.fn.destroyInfinite = function() {
return this.each(function() {
var infinite = $(this).data("infinite");
if(infinite && infinite.detachEvents) infinite.detachEvents();
});
}
}($);
下面是页面代码
<div id="parent" class="list">
<!--<div class="weui-cells">
<a class="weui-cell weui-cell_access" href="javascript:;">
<div class="weui-cell__bd">
<p>AA</p>
</div>
<div class="weui-cell__ft update">2018-01-01 <span class="state">A</span></div>
</a>
</div>-->
</div>
<div id="loadmore" class="weui-loadmore">
<i class="weui-loading"></i>
<span class="weui-loadmore__tips">上拉加载</span>
</div>
//上拉加载
var access = localStorage.getItem('login');
var loading = false;
var count = 0;
pullup ();
pullup ();
pullup ();
$(document.body).infinite(100).on("infinite", function() {
if(loading) return;
loading = true;
setTimeout(function(){
pullup ();
},1500);
});
function pullup (){
count++;
var request_data = {
'access_token': access,
'page': count
};
$.ajax({
type: 'post',
url: api.domain + list,
data: request_data,
success: function(res){
if(res.status == 1) {
if(res.data.data.length > 0) {
var n = res.data.data.length;
var $content = $('<div class="weui-cells"></div>');
for(var i = 0; i < n; i++) {
var health = 'v';
var $list = $('<a class="weui-cell weui-cell_access" href="/home/report/' + res.data.data[i].id + '">' +
'<div class="weui-cell__bd">' +
'<p>' + res.data.data[i].username + '</p>' +
'</div>' +
'<div class="weui-cell__ft update">' + res.data.data[i].created_at + ' <span class="state">' + health + '</span></div>' +
'</a>');
$list.appendTo($content);
}
$content.appendTo($('#parent'));
//$(document.body).destroyInfinite();
loading = false;
} else {
//$(document.body).destroyInfinite();
loading = false;
$.toast('没有更多');
$('#loadmore').addClass('hide');
}
} else {
$.toast(res.msg, 'cancel');
}
},
});
}