[英]Click on html element doesn't work after setTimeout()
I have a userscript which loads a list of buttons on a page.我有一个用户脚本,它在页面上加载按钮列表。 It then tries to click all the buttons one by one in a loop.然后它会尝试在一个循环中一个一个地单击所有按钮。 This is my function.这是我的 function。
const clickButtons = async function(listButtons) {
const filteredButtons = Array.from(listButtons).filter(x => shouldButtonBeClicked(x.innerText));
for (let i = 0; i < filteredButtons.length; i++) {
filteredButtons[i].click();
}
}
The above piece of code works as expected.上面的代码按预期工作。 No issues.没有问题。 All the buttons are clicked.所有按钮都被单击。
But, when I try to add some wait time before every click, it doesn't work.但是,当我尝试在每次点击之前添加一些等待时间时,它不起作用。 None of the buttons get clicked.没有一个按钮被点击。 Notice wait() on first line inside the loop注意循环内第一行的 wait()
const wait = async function(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
const clickButtons = async function(listButtons) {
const filteredButtons = Array.from(listButtons).filter(x => shouldButtonBeClicked(x.innerText));
for (let i = 0; i < filteredButtons.length; i++) {
await wait(1000);
filteredButtons[i].click();
}
}
What am I missing here?我在这里想念什么?
Resolving the promise with a click should work单击即可解决 promise 问题
await wait(1000).then((res)=> filteredButtons[i].click());
You can try this:你可以试试这个:
const wait = async function(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
const clickButtons = async function(listButtons) {
const filteredButtons = Array.from(listButtons).filter(x => shouldButtonBeClicked(x.innerText));
filteredButtons.forEach(async function (filteredButton, index) {
await wait(1000);
filteredButtons[index].click();
// OR
// filteredButton.click();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.