So I'm currently creating a test script and one of the scenario is clicking different sets of buttons based on the aria-label.
So a pretty straight forward JS where I do a query selector all and click all the needed buttons but for some reason only the first button gets click.
At first I thought it might have been a race condition so I added a delay
My code:
var share = document.querySelectorAll("[aria-label='SubmitDoc']"); for (let i = 0, len = share.length; i < len; i++) { setTimeout(function () { console.log(share[i]); share[i].click(); },2000 * i); }
<div aria-label="SubmitDoc" class="btn-submit" role="button" tabindex="0"></div> <div aria-label="SubmitForm" class="btn-submit" role="button" tabindex="0"></div> <div aria-label="SubmitClass" class="btn-submit" role="button" tabindex="0"></div> <div aria-label="SubmitDoc" class="btn-submit" role="button" tabindex="0"></div> <div aria-label="SubmitForm" class="btn-submit" role="button" tabindex="0"></div> <div aria-label="SubmitClass" class="btn-submit" role="button" tabindex="0"></div> <div aria-label="SubmitFinal" class="btn-submit" role="button" tabindex="0"></div> <div aria-label="SubmitFinal" class="btn-submit" role="button" tabindex="0"></div>
Am I missing something?
You are basically missing a closure. Because you are running a click in a setTimeout, by the time it fires the loop has already run and the value of i is already its maximum value. You can solve this like so:
var submitDoc = document.querySelectorAll("[aria-label='SubmitDoc']")
var doClick = function (node, delay) {
setTimeout(function () {
node.click();
}, delay);
}
for (let i = 0, len = share.length; i < len; i++) {
doClick(share[i], 2000 * i);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.