首页 > 解决方案 > 如何使用 setTimeout 在 jquery 中循环?

问题描述

我有一张桌子,我正在尝试创建一个书签,它将单击每一行并在计时器上运行一些代码。每个选项卡都需要一段时间才能加载。如果我只专注于一行,我的代码就会起作用,那么当我尝试让它循环时,我的问题就会出现。

我目前的思考过程是

javascript:(function(){
var TableLength = $("#summaryTable tr").length;
var j=1;

nameOfFunction = function(){
if(j === TableLength){break;}
$("#summaryTable tr:nth-child("+j+")").click();
setTimeout(function(){
$i("#tab1")[0].click();
J++;},1000);
setTimeout(nameOfFunction,2000);
};
nameOfFunction();
})();

我之前的想法在哪里

javascript:(function(){
var TableLength = $("#summaryTable tr").length;
var j;

for (j=1; j < TableLength; j++){
setTimeout(function(){
$("#summaryTable tr:nth-child("+j+")").click();
setTimeout(function(){
$i("#tab1")[0].click();},1000);
}, 1000};
}
})();

该表有一个标题,因此第一行是第 1 行而不是 0。

标签: javascriptjquery

解决方案


是的,你的代码没有按照你说的去做。

let TableLength = $("#summaryTable tr").length;

let rows = Array.from(document.querySelectorAll("summeryTable>tr")); //not 100% on the '>'
rows.forEach(row=>{
   if(i==0){}
   else
       {
       row.click();
       setTimeout(function()
           {
           $("#tab1")[0].click();
       },1000);
   }
   i++;
});

但即使这样也行不通,因为 $("#tab1") 似乎是一个重复的 id(禁止),除非它一遍又一遍地单击同一个元素......而不是新生成的选项卡///

应该是 $(#tab${i/j/whatever iterator you use}代替。

我不确定这是否是你的意思。但这就是我会使用的方法。


推荐阅读