javascript - 在页面不断更新时使用 jQuery 的 .each 功能
问题描述
我整天都在努力寻找解决方案,但想不出一个我可以开始工作的好方法。
基本上,我编写了一些 jQuery/javascript 代码,为网页上的某些项目运行 each() 循环。这很好用,但是当您滚动到底部时,它运行的页面会更新,从而添加更多结果。目前,我的脚本只能通过页面上加载的项目。我希望它能够浏览所有已加载的内容,然后滚动到底部并浏览所有新结果并不断重复此过程。
我尝试了很多不同的解决方案,但似乎无法做出一个很好的解决方案。
任何帮助都将不胜感激。
谢谢 :)
编辑:
以下是我迄今为止尝试过的一些概念:
将代码放在一个while循环中并添加一个偏移量,以便它跳过它已经过去的所有项目
var a = 0; var offset = 0; while (a == 0) { jQuery('.Grid-cell .js-stream-item .ProfileCard').each(function (i, ele) { if (i >= offset) { //Run script } }); offset = offset + 18; //18 is how many new items are added each time setTimeout(function () { jQuery('html, body').animate({scrollTop:$(document).height()}, 'fast'); //To scroll to the bottom }, 5000); }
将代码放在while循环中但没有偏移
(与之前的类似,但删除了偏移,因为我认为它可能会超出已经完成的偏移)
这个有点实验性,因为在之前的尝试失败后我变得绝望。基本上,我添加了一个隐藏的复选框,然后将我的脚本和每个循环放在一个函数中。然后,每当单击复选框时,它将运行运行我的脚本的函数,一旦每个循环完成,它将滚动到页面底部并单击复选框以使函数再次运行
$( ".Footer-copyright" ).append( "<input type='checkbox' class='functionclass' style='display:none' value='no' />" ); jQuery(".functionclass").on("click", function() { myfunction(); }) function myfunction() { jQuery('.Grid-cell .js-stream-item .ProfileCard').each(function (i, ele) { //Run script }); jQuery('html, body').animate({scrollTop:$(document).height()}, 'fast'); jQuery(".functionclass").click(); } jQuery(".functionclass").click();
解决方案
所以我相信我已经找到了解决问题的方法。这并不是有史以来最干净的解决方案,但它似乎可以完成工作。基本上,我将任务放在 setInterval() 函数中,因此它现在每 5 秒完成一次任务,并在 15 个任务后滚动到底部。这允许它在每次运行时获取所有元素的更新列表。这是任何好奇的人的代码:
var i = 0;
task = setInterval(function(){
var elements = jQuery(".Grid-cell .js-stream-item .ProfileCard"); //Gets all of the elemnts
var element = jQuery(elements[i]); //Gets the element for the attempt number
//Completes task
if (i % 15 === 0){
jQuery('html, body').animate({scrollTop:$(document).height()}, 'fast'); //Scrolls to bottom when attempt number is divisible by 15
}
i++;
}, 5000);
推荐阅读
- azure-web-app-service - Azure App Service Web Worker 使用什么帐户?(O365 集成)
- mysql - 检索关注的共享帖子 sql、mysql
- vba - VBA遍历列并附加到单元格
- python-3.x - 未解决的参考“MediaFileUpload”
- database - 除了简单的算法之外,是否有一种算法可以按到向量的距离对数据库表进行排序或过滤?
- java - SSL环境下的SpringBoot+Eureka+CloudConfig
- angular - 角度服务 - 对象不可分配给数组
- regex - 使用“sed”删除包含某些内容的行和下一行
- angular - docker-compose 中的 Angular js 6 405(不允许的方法)
- excel - 在excel中的字符之间提取和复制文本