我有一个for循环,再次运行一个节点列表。我试图遍历节点列表并触发单击,然后设置间隔以等待弹出窗口,然后我要在弹出窗口中触发单击。
我的问题是我需要每次迭代都要等到弹出窗口被加载,然后单击弹出窗口中的项才能进行下一次迭代。希望这有道理。
这是我的代码。
let checkSteats = () => {
const seats = document.querySelectorAll(seatSectionSelector);
if (seats.length < maxSeatCount) {
maxSeatCount = seats.length;
}
if (seats.length > 0) {
[].forEach.call(seats, (seat, index) => {
/**
* WE NEED TO CLICK WAIT FOR A CHANGE IN THE RESPONSE OR POP UP BEFORE WE GO INTO THE NEXT ITERATION
*/
console.log(seat)
if ((index+1) <= maxSeatCount) {
seat.dispatchEvent(
new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true,
buttons: 1
})
);
const popupInterval = setInterval(() => {
const popupBtn = document.querySelector('.ticket-option__btn');
if (popupBtn) {
popupBtn.click();
clearInterval(popupInterval);
}
}, 100)
}
});
}
};
答案 0 :(得分:2)
您想使用一个基本队列,在其中使用shift()从数组的前面拉出项目
var myArray = [1, 2, 3, 4]
function nextItem() {
var item = myArray.shift();
window.setTimeout(function() {
console.log(item);
if (myArray.length) nextItem();
}, 1000)
}
nextItem()
因此,在您的情况下,清除间隔时将调用nextItem()。您可以通过将html集合转换为数组来获得转变
const seats = Array.from(document.querySelectorAll(seatSectionSelector));
function nextItem() {
var seat = seats.shift();
seat.dispatchEvent(...);
const popupInterval = setInterval(() => {
...
if (popupBtn) {
...
if (seats.length) nextItem();
}