最近公司的微信端项目有个下拉加载更多的功能,以前也做过一个类似的,传当前页面给后台然后后台返回给对应的数据。这次项目做完后,测试的时候发现一个bug就是部分数据会重复加载,当时还以为是下拉过快引起的= =
  先上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| $(document).on("scroll",function(){ var scrollheight=$(document).scrollTop(); var screenheight=document.documentElement.clientHeight; var domheight=$(document).height(); act_id=$(".box").last().attr("id"); supply_id=$(".title .active").attr("id"); var imgs = document.getElementsByClassName('lazyimg'); if (scrollheight+screenheight>=domheight) { getcontent(act_id,supply_id,stree_id,price_level,price_level_type,room,half,toilet,build_area,house_age,floor_min,housetype_id); } for (var j = 0; j < imgs.length; j++) { var imgheight=imgs[j].offsetTop; console.log(imgheight+"======"+(scrollheight+screenheight)); if (imgheight< scrollheight+screenheight) { imgs[j].src=imgs[j].getAttribute("data-src"); } } })
|
当时的代码只判断了下拉滚动的距离是否大于等于该图片到顶部的距离,但是打开谷歌浏览器就看请求的时候,发现请求了两次;然后百度了一翻,搜到一个答案:https://segmentfault.com/q/1010000000668595 ;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| var loading = false; $(window).on('scroll', function () { if($(document).scrollTop() + $(window).height() > $(document).height() - 100){ if(!loading){ push(); } }; }) function push() { loading = true; $.ajax(...) complete:(function () { loading = false; }); }
|
用了这个标志变量后,就可以在下拉滚动的距离是否大于等于该图片到顶部的距离的判断if语句中再加道安全锁 && !loading,来防止ajax多次请求。