简体   繁体   English

在 for 循环中单击 function 仅影响最后一次迭代

[英]Click function inside for loop only effecting last iteration

I'm having an issue with the code below, the function is to find click on all links that contain ".gif".我对下面的代码有问题,function 是要找到点击所有包含“.gif”的链接。 The code seems to iterate but only clicks the last iteration (when i=20), after some research it seems to be an issue with "hoisting" although Im unsure how to edit my code to fix the issue.代码似乎在迭代,但只点击最后一次迭代(当 i=20 时),经过一些研究,这似乎是“提升”的问题,尽管我不确定如何编辑我的代码来解决这个问题。

for (let i = 0; i < 20; i++) {
    if (document.getElementsByTagName("a")[i].hasAttribute("href")) {

        if (document.getElementsByTagName("a")[i].getAttribute("href").includes(".gif")) {

            document.getElementsByTagName("a")[i].click();
        }
    }
}

I don't see any obvious scoping/hoisting issues in your code, but there's no reason for repeated calls to get all elements just to take the i -th element and throw the rest away.我在您的代码中没有看到任何明显的范围界定/提升问题,但是没有理由重复调用获取所有元素只是为了获取第i个元素并将 rest 扔掉。 Try making one selection, then .filter out the ones matching your predicate then .forEach the elements that passed the filter and click them.尝试进行一个选择,然后.filter掉与您的谓词匹配的那些,然后.forEach通过过滤器的元素并单击它们。 If you had any variable issues, using self-contained array functions should resolve the problem.如果您有任何变量问题,使用自包含数组函数应该可以解决问题。

 [...document.querySelectorAll("a[href]")].filter(e => e.getAttribute("href").endsWith(".gif")).forEach(e => e.click());
 <a href="foo.gif">foo</a> <a href="bar.gif">bar</a> <a href="baz.png">baz</a>

The wildcard $ approach from Kinglish is better , but I'll leave this up for the explanation for now. Kinglish 中的通配符$方法更好,但我暂时将其留作解释。

Building off of @ggorlen's solution, you could further refine it using the wildcard $ css selector在@ggorlen 的解决方案的基础上,您可以使用通配符$ css 选择器进一步完善它

document.querySelectorAll("a[href$='.gif']").forEach(e => e.click());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM