javascript 按顺序单击每个元素,并在每次单击之间等待

qojgxg4l  于 2022-12-17  发布在  Java
关注(0)|答案(2)|浏览(135)

我有一个querySelectorAll列表,看起来像这样:

NodeList(676) [div.tile.tooltip, div.tile.tooltip, div.tile.tooltip.tooltipstered,
 div.tile.tooltip, div.tile.tooltip, div.tile.tooltip, div.tile.tooltip,
 div.tile.tooltip.tooltipstered, div.tile.tooltip.tooltipstered, div.tile.tooltip,
 div.tile.tooltip, div.tile.tooltip.tooltipstered,  ...

每个都是一个小部件,我可以在网站上点击,然而,我想点击每个,但与计时器延迟每次点击几秒钟.我已经尝试了以下:

var tile = document.querySelectorAll(".perspectivesInner.clearFix > div");
var t = new Array();
for( let i = 0 ; i < tile.length ; i++ ) {
    (function(){    // create a closure (new scope)
      var _i = i;   // make a local copy of `i` from the outer scope
      t[i] = setTimeout( function(){return tile[i].click()}, i*2000 );
    })();
  }

这点击了所有内容,但我登录到了控制台:
VM2642:5未捕获的类型错误:无法在5:52读取未定义的属性(阅读“click”)
清洁替代品是什么?

mklgxw1f

mklgxw1f1#

下面是一种更ES6的编写方法,可以解决您的问题。

let tiles = document.querySelectorAll(".perspectivesInner.clearFix > div");
tiles.forEach((tile,i) => {
  setTimeout(() => tile.click(), i * 1000);
});
<div class="perspectivesInner clearFix">
  <div onclick="console.log(this.innerText)">One</div>
  <div onclick="console.log(this.innerText)">Two</div>
  <div onclick="console.log(this.innerText)">Three</div>
  <div onclick="console.log(this.innerText)">Four</div>
  <div onclick="console.log(this.innerText)">Five</div>
</div>
myzjeezk

myzjeezk2#

我认为您可以使用Promises非常简单地解决这个问题
使用异步等待方法,您可以像这样在每次单击之间等待随机时间

// #region utility
function randomIntFromInterval(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

async function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
// #endregion

async function clickElements(selector) {
  const elements = document.querySelectorAll(selector);
  for (const element of elements) {
    element.click();
    await wait(randomIntFromInterval(1000, 2000));
  }
}

clickElements('.perspectivesInner.clearFix > div');
<div class="perspectivesInner clearFix">
  <div class="perspective" onclick="console.log('0')">0</div>
  <div class="perspective" onclick="console.log('1')">1</div>
  <div class="perspective" onclick="console.log('2')">2</div>
  <div class="perspective" onclick="console.log('3')">3</div>
  <div class="perspective" onclick="console.log('4')">4</div>
  <div class="perspective" onclick="console.log('5')">5</div>
  <div class="perspective" onclick="console.log('6')">6</div>
  <div class="perspective" onclick="console.log('7')">7</div>
  <div class="perspective" onclick="console.log('8')">8</div>
  <div class="perspective" onclick="console.log('9')">9</div>
</div>

相关问题